package com.jlkf.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.PseudoColumnUsage;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.servlet.http.HttpServletRequest;

import org.apache.tools.ant.taskdefs.SendEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.jlkf.common.Constant;
import com.jlkf.common.googleMap.GoogleMileage;
import com.jlkf.common.googleMap.GoogleMileageElementsObj;
import com.jlkf.common.googleMap.Routes;
import com.jlkf.common.redis.service.JedisClient;
import com.jlkf.dao.CarCaculationMapper;
import com.jlkf.dao.CarCaculationPointChargesMapper;
import com.jlkf.dao.CityRecordMapper;
import com.jlkf.dao.ConfigManagerMapper;
import com.jlkf.dao.DriverAccessoryMapper;
import com.jlkf.dao.DriverStartServerMapper;
import com.jlkf.dao.EstimateFloatMapper;
import com.jlkf.dao.GisRecordMapper;
import com.jlkf.dao.NoSuccessfulRecordIsPaidMapper;
import com.jlkf.dao.OrderCancelMapper;
import com.jlkf.dao.OrderChargeDetailMapper;
import com.jlkf.dao.OrderItemsMapper;
import com.jlkf.dao.PinpayRecordMapper;
import com.jlkf.dao.PlayTheRewardRewardMapper;
import com.jlkf.dao.PreAuthorizationAndCaptureSteponeMapper;
import com.jlkf.dao.PreAuthorizationAndCaptureSteptwoMapper;
import com.jlkf.dao.RefundRecordMapper;
import com.jlkf.dao.StarRemarkMapper;
import com.jlkf.dao.StrokeRecordMapper;
import com.jlkf.dao.SugFeedbackMapper;
import com.jlkf.dao.UserBrankMapper;
import com.jlkf.dao.UserConfirmTheOrderingMapper;
import com.jlkf.dao.UserCouponMapper;
import com.jlkf.dao.UserMapper;
import com.jlkf.dao.UserMessageMapper;
import com.jlkf.fatZebra.ReturnReference;
import com.jlkf.pojo.CarCaculation;
import com.jlkf.pojo.CarCaculationPointCharges;
import com.jlkf.pojo.CityRecord;
import com.jlkf.pojo.ConfigManager;
import com.jlkf.pojo.DriverAccessory;
import com.jlkf.pojo.EstimateFloat;
import com.jlkf.pojo.GisRecord;
import com.jlkf.pojo.OrderCancel;
import com.jlkf.pojo.OrderChargeDetail;
import com.jlkf.pojo.OrderItems;
import com.jlkf.pojo.PinpayRecord;
import com.jlkf.pojo.PlayTheRewardReward;
import com.jlkf.pojo.PreAuthorizationAndCaptureStepone;
import com.jlkf.pojo.PreAuthorizationAndCaptureSteptwo;
import com.jlkf.pojo.RefundRecord;
import com.jlkf.pojo.StarRemark;
import com.jlkf.pojo.StrokeRecord;
import com.jlkf.pojo.SugFeedback;
import com.jlkf.pojo.User;
import com.jlkf.pojo.UserBrank;
import com.jlkf.pojo.UserConfirmTheOrdering;
import com.jlkf.pojo.UserCoupon;
import com.jlkf.pojo.UserMessage;
import com.jlkf.service.util.Distance;
import com.jlkf.service.util.FireBaseUtil;
import com.jlkf.service.util.LanguageUtils;
import com.jlkf.service.util.RegexUtil;
import com.jlkf.service.util.SendmailUtil;
import com.jlkf.service.util.StringTools;
import com.jlkf.service.OrderItemsService;
import com.jlkf.service.UserService;
import com.jlkf.view.Driver;
import com.jlkf.view.NearDriver;
import com.jlkf.view.OrderItemsAndDriver;
import com.jlkf.view.OA.OAStarRemark;
import com.platform.server.response.pojo.ReturnData;
import com.platform.server.util.DateUtil;
import com.platform.server.util.HttpRequestUtil;
import com.platform.server.util.RandomUtil;

import io.practiceinsight.pinpayments.pojo.ErrorMessage;
import io.practiceinsight.pinpayments.pojo.ErrorResponse400;
import io.practiceinsight.pinpayments.pojo.ErrorResponseCard;
import io.practiceinsight.pinpayments.pojo.ResponseBalance;
import io.practiceinsight.pinpayments.pojo.ResponseCharges;
import io.practiceinsight.pinpayments.pojo.ResponseTransfers;
import io.practiceinsight.pinpayments.utils.PinPayHttpUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Service
public class OrderItemsServiceImpl implements OrderItemsService {

	@Autowired
	private OrderItemsMapper orderItemsMapper;
	@Autowired
	private UserCouponMapper userCouponMapper;
	@Autowired
	private UserBrankMapper userBrankMapper;
	@Autowired
	private CarCaculationMapper carCaculationMapper;
	@Autowired
	private EstimateFloatMapper estimateFloatMapper;
	@Autowired
	private GisRecordMapper gisRecordMapper;
	@Autowired
	private CityRecordMapper cityRecordMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private StarRemarkMapper starRemarkMapper;
	@Autowired
	private StrokeRecordMapper strokeRecordMapper; // 订单行程记录
	@Autowired
	private DriverAccessoryMapper driverAccessoryMapper;
	@Autowired
	private OrderCancelMapper orderCancelMapper;
	@Autowired
	private OrderChargeDetailMapper orderChargeDetailMapper;
	@Autowired
	private CarCaculationPointChargesMapper carCaculationPointChargesMapper;
	@Autowired
	private RefundRecordMapper refundRecordMapper;
	@Autowired
	private UserMessageMapper userMessageMapper;
	@Autowired
	private ConfigManagerMapper configManagerMapper;
	@Autowired
	private DriverStartServerMapper driverStartServerMapper;
    @Autowired
	private UserConfirmTheOrderingMapper userConfirmTheOrderingMapper;
	@Autowired
	private JedisClient jedisClient;
	@Autowired
	private NoSuccessfulRecordIsPaidMapper noSuccessfulRecordIsPaidMapper;
	@Autowired
	private PlayTheRewardRewardMapper playTheRewardRewardMapper;
	@Autowired
	private JedisPool jedisPool; 
	@Autowired
	private SugFeedbackMapper sugFeedbackMapper;
	@Autowired
	private PinpayRecordMapper pinpayRecordMapper;
	@Autowired
	private UserService userService;
	

	@Override
	public ReturnData getMyuncompletedOrder(Long uId) {
		Map<String, Object> map = new HashMap<>();
		map.put("uId", uId);// 查询我的订单
		Integer[] orderStatus = { 2, 3, 4, 5, 6, 14,11 };// 未完成支付
		map.put("orderStatus", orderStatus);
		try {
			List<OrderItems> list = orderItemsMapper.getOrderItems(map);

			return new ReturnData(list, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}
	}

	@Override
	public Object driverGetMyuncompletedOrder(Long driverId) {
		Map<String, Object> map = new HashMap<>();
		map.put("dirberId", driverId);// 查询我的订单
		Integer[] orderStatus = {  2, 3, 4, 5, 6, 7, 15 };// 未完成支付
		map.put("orderStatus", orderStatus);
		Integer time = 0;
		ConfigManager cm=null;
		Jedis jedis = null;
		if(jedis==null){
			jedis =jedisPool.getResource();
		}
		try {
			List<OrderItems> list = orderItemsMapper.getOrderItems(map);
			/*List<ConfigManager> cm = configManagerMapper.getList();
			if (cm.size() > 0) {
				time = cm.get(0).getOrderTime();
			}*/
			String configManager=jedis.get("configManager");
			if(StringTools.isEmpty(configManager)){
				 cm = configManagerMapper.selectByPrimaryKey(1);
					JSONObject jo = JSONObject.fromObject(cm);
					jedis.set("configManager", jo.toString());
					time = cm.getOrderTime();
			}else{
				JSONObject jo = JSONObject.fromObject(configManager);
				cm = (ConfigManager) JSONObject.toBean(jo, ConfigManager.class);
				time = cm.getOrderTime();
			}
			for (OrderItems oi : list) {
				List<DriverAccessory> l = driverAccessoryMapper.getUserCars(driverId);
				for (DriverAccessory da : l) {
					if (da.getIsUse() == 1) {
						oi.setCarId(da.getId());
					}
				}
				oi.setConfigTime(time);
				oi.setNowTime(new Date().getTime());
			}
			return new ReturnData(list, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}finally {
			if(jedis!=null){
				jedis.close();
			}
		}
	}

	// toll_station 收费站 经纬度
	@Override
	public ReturnData getHomePageEstimate(String mileage, String time, Long uId, String trafficJamTime,
			List<String> toll_station,String departurePosition,String arrivedPosition) {
		Map<String, Object> map = new HashMap<>();
		map.put("uId", uId);
		map.put("isUse", 1);// 是否使用 1未使用 2已使用
		map.put("isOutOfDate", 1);// 是否过期 1未过期 2已过期
		Jedis jedis = null;
		if(jedis==null){
			jedis =jedisPool.getResource();
		}
		double price_time_config=0.0;	
		try {
			List<UserCoupon> list = userCouponMapper.getCoupon(map);// 获取我的优惠卷列表
																// 最先过期的最先使用
//			ConfigManager cm=configManagerMapper.selectByPrimaryKey(1);//查询配置信息
			String configManager=jedis.get("configManager");
			ConfigManager cm=null;
			if(StringTools.isEmpty(configManager)){
				 cm = configManagerMapper.selectByPrimaryKey(1);
					JSONObject jo = JSONObject.fromObject(cm);
					jedis.set("configManager", jo.toString());
					price_time_config=cm.getPrice_time_config();
			}else{
				JSONObject jo = JSONObject.fromObject(configManager);
				cm = (ConfigManager) JSONObject.toBean(jo, ConfigManager.class);
				price_time_config=cm.getPrice_time_config();
			}
			map.put("isDefault", 1);// 默认支付的卡
			List<UserBrank> ubList = userBrankMapper.getUserBrank(map);
			Map<String, Object> resultMap = new HashMap<>();
			UserBrank ub = null;
			UserCoupon mycoupon = null;
			if (ubList.size() > 0) {
				ub = ubList.get(0);
			}
			if (list.size() > 0) {
				mycoupon = list.get(0);
			}
			// if(list.size()>0){ mycoupon = list.get(0); }
			EstimateFloat ef = estimateFloatMapper.getFloat();// 浮动区间
			resultMap.put("userBrank", ub);// 默认支付的银行卡
			/**
			 * 所有用车的规则 堵车时长=堵车时长-（正常时长*1.1） 堵车费=堵车时长*系统配置堵车费 时长费 = 正常时长*系统配置时长费
			 * 里程费=里程*系统配置里程费 预估价=堵车费+时长费+里程费+起步价【系统配置起步价】
			 */
			Map<String,Object> maps=getTt(departurePosition, arrivedPosition, time);//获取堵车时长
			trafficJamTime=(String) maps.get("trafficJamTime");//堵车时长
//			time = (String) maps.get("time");//预计时长
			// 堵车时长
			Integer the_traffic_time = Integer.parseInt(trafficJamTime);
			// 正常时长
			Integer the_normal_time = Integer.parseInt(time);
			// 堵车时长 比正常多出来的时长
			Integer traffic_time = the_traffic_time - the_normal_time;//预估时 多出来的时长 
			//需要收取的堵车费的时长
			Integer tt=(int) (traffic_time-(the_normal_time*price_time_config));
			// 里程
			Double mileage_num = Double.parseDouble(mileage) / 1000;
			List<Map<String, Object>> money = new ArrayList<>();
			List<CarCaculation> ccmlist = carCaculationMapper.getCarCaculation(map);// 计价规则
			for (CarCaculation carCaculation : ccmlist) {// 针对每一个规则
				Double congestion_pricing = tt * carCaculation.getTrafficJamPrice();// 堵车费
				if (congestion_pricing <= 0) {
					congestion_pricing = 0.0;
				}
				Map<String, Object> m =estimateReturnMap(congestion_pricing,the_normal_time,mileage_num,carCaculation,ef,mycoupon);//获取预估价
				m.put("mycoupon", mycoupon);//可抵扣优惠劵 默认使用最先过期
				money.add(m);
			}
			resultMap.put("estimatePrice", money);// 预估价
			return new ReturnData(resultMap, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}finally {
			if(jedis!=null){
				jedis.close();
			}
		}
	}
	//获取堵车时长
	private Map<String,Object> getTt(String departurePosition,String arrivedPosition,String time){
		Map<String,Object> map=new HashMap<>();
		String trafficJamTime="0";time="0";
		if(!StringTools.isEmpty(departurePosition)){
			String result =getStandardTime(departurePosition, arrivedPosition);//获取堵车费
			JSONObject jo = null;
			if (result != "") {
				jo = JSONObject.fromObject(result);
				if (!jo.isNullObject() && "OK".equals(jo.get("status"))) {// 成功
					System.out.println("访问google地图返回状态：" + jo);
					JSONArray ja = net.sf.json.JSONArray.fromObject(jo.get("routes"));
					System.out.println("routes=" + ja);
					// 公里里程
					if (ja.size() > 0) {
						JSONObject llrg = (JSONObject) ja.get(0);// 里程计算 // legs
						System.out.println("legs=" + llrg);
						if (!llrg.isNullObject()) {
							JSONArray legss = JSONArray.fromObject(llrg.get("legs"));//
							if (legss.size() > 0) {
								JSONObject legs1 = (JSONObject) legss.get(0);
								if (!legs1.isNullObject()) {
									JSONObject jdit = (JSONObject) legs1.get("duration");//标准时长
									JSONObject jdit1 = (JSONObject) legs1.get("duration_in_traffic");//堵车时长
									System.out.println("访问google地图返回标准时长：" + jdit);
									System.out.println("访问google地图返回堵车时长：" + jdit1);
									if (!jdit.isNullObject()) {//
//										time =String.valueOf((Integer) jdit.get("value"));
										Integer min=(Integer.parseInt(time)/60);
//										Integer tt=(int) ((min*price_time_config)+min);
										time=String.valueOf(min);//分钟
									}
									if (!jdit1.isNullObject()) {//
										Integer ct=(Integer) jdit1.get("value")/60;
										trafficJamTime =String.valueOf(ct);//分钟
									}
								}
							}
						}
					}
				}
			}
		}
		map.put("trafficJamTime", trafficJamTime);
		map.put("time", time);
		return map;
	}
	//预估价返回的map对象
	public Map<String, Object> estimateReturnMap(Double congestion_pricing,Integer the_normal_time,Double mileage_num,CarCaculation carCaculation,EstimateFloat ef,UserCoupon mycoupon){
		Double roadPrice = 0.0;// 路桥费
		Double concierge_price=0.0;String qj="";String pd="";
		Double how_fee = the_normal_time * carCaculation.getTimePrice();// 时长费
		Double mileage_fee = mileage_num * carCaculation.getMileagePrice();// 里程费
		Double startPrice = carCaculation.getStartPrice();// 起步价
		Double couponMoney=0.0;
		DecimalFormat df = new DecimalFormat("######0.00");
		Map<String, Object> m = new HashMap<>();
		if (1 == carCaculation.getCarType()) {// fab ONE
			m.put("type", 1);
			m.put("carType", "fab ONE");
		} else if (2 == carCaculation.getCarType()) {// fab
			m.put("type", 2);
			m.put("carType", "fab");
		} else if (3 == carCaculation.getCarType()) {// fbc PRO
			m.put("carType", "fab PRO");
			m.put("type", 3);
		}else if(4 == carCaculation.getCarType()){//concierge
			m.put("carType", "concierge");
			m.put("type", 4);
			concierge_price=carCaculation.getExtraMoney();
		}
		m.put("congestion_pricing", df.format(congestion_pricing));// 堵车费
		m.put("how_fee", df.format(how_fee));// 时长费
		m.put("mileage_fee", df.format(mileage_fee));// 里程费
		m.put("startPrice", df.format(startPrice));// 起步价
		m.put("minimumFare", df.format(carCaculation.getMinimumFare()));// 最低消费
		double estimatePrice = startPrice + mileage_fee + how_fee+congestion_pricing ;// 预估价
		Double estimatePrice1=  roadPrice+carCaculation.getBookingFee();
		if(estimatePrice<carCaculation.getMinimumFare()){//里程 时长 起步价小于最低消费
			estimatePrice=carCaculation.getMinimumFare();
//			qj=carCaculation.getMinimumFare()+"";
//			pd=carCaculation.getMinimumFare()+"";
		}
       if(mycoupon!=null){
    	   couponMoney=mycoupon.getCouponMoney().doubleValue();
		}
       estimatePrice = (estimatePrice1+estimatePrice)-couponMoney;
       if(estimatePrice<0){
    	   estimatePrice=0;
       }
//		Integer startFloat = ef.getStartFloat();// 浮动开始比例
		Integer endFloat = ef.getEndFloat();
		double endf = (double) (endFloat / Double.valueOf(100));
//		double sf = (double) (startFloat / Double.valueOf(100));
//		Double sestimatePrice = sf * estimatePrice;
		Double eestimatePrice = endf * (estimatePrice1+estimatePrice);//结束区间多出来的费用
		Double startEstimatePrice = estimatePrice+estimatePrice1+concierge_price;//预估价整体费用
		Double endEstimatePrice = estimatePrice+estimatePrice1+eestimatePrice+concierge_price;// 结束区间的预估价
		 qj=startEstimatePrice.intValue() + "-" + endEstimatePrice.intValue();
		 if(endEstimatePrice.intValue()-startEstimatePrice.intValue()==0){
			 qj=endEstimatePrice.intValue()+"";
		 }
		 
		 pd=df.format((estimatePrice+estimatePrice1+concierge_price));//concierge_price是比较最低消费之后加上的
		m.put("startEstimatePrice", startEstimatePrice.intValue());
		m.put("endEstimatePrice", endEstimatePrice.intValue());// 结束预估价
		m.put("estimatePrice_interval", qj);// 预估价区间
		m.put("totals", pd);
		m.put("estimatePrice", df.format(estimatePrice+estimatePrice1));// 预估价
		m.put("bookingFee", df.format(carCaculation.getBookingFee()));
		m.put("concierge_price", df.format(concierge_price));
		return m;
	}

	// 确认下单 此时需冻结银行卡中的金额
	/**
	 * 提供 ubId 出发地地址（经纬度） 目的地（经纬度） 预估价最大金额【estimatePrice】 需要坐车的车型
	 * name，telephone，cityId，city，car_type、estimate_price，
	 * 
	 * 返回状态说明 204 支付接口调用不通，转json错误，返回错误 201 支付返回错误码 207 支付返回response对象获取失败 203
	 * authorized 支付 失败 206 服务器保存支付记录失败 209 订单新增失败
	 */
	@Override
	public ReturnData confirmTheOrder(String json) {
		// carType uId estimatePrice//传预估价区间结束金额
		OrderItems orderItems = StringTools.json2Obj(json, OrderItems.class);
		if (orderItems == null) {
			return new ReturnData(201, LanguageUtils.returnLan(2, "list_empty"));
		}
		Integer language = 2;
		if (orderItems.getLanguage() != null) {
			language = orderItems.getLanguage();
		}
		int code = 200;
		String msg = "success";Jedis jedis=null;
		// 新增之后 返回给前端订单信息
		try {
			Map<String, Object> map = new HashMap<>();
			Integer[] wwc = { 2, 3, 4, 5, 6, 7, 11, 15 };
			map.put("uId", orderItems.getuId());
			map.put("orderStatus", wwc);// 未完成
			UserBrank ub = userBrankMapper.selectByPrimaryKey(orderItems.getUbId());// 银行卡信息
			String orderNo = getOrderNo();// 获取订单
			User u = userMapper.selectByPrimaryKey(orderItems.getuId());
			/// 。。。。。。。。。。以下为冻结支付、、、
              //////////////////////支付///////////////
			if (orderItems.getId() != null) {// 修改途径
				OrderItems ooi = orderItemsMapper.selectByPrimaryKey(orderItems.getId());//查询订单
				orderNo = ooi.getOrderNo();
				if(orderItems.getTjdOrmdd() != null && orderItems.getTjdOrmdd() == 1){
					orderItems.setTujingdianCount(ooi.getTujingdianCount()+1);
				}else{
					orderItems.setDestinationCount(ooi.getDestinationCount()+1);
				}
				int num = orderItemsMapper.updateByPrimaryKeySelective(orderItems);
				if (num == 0) {
					code = 209;
					msg = LanguageUtils.returnLan(language, "update_orders_failed");
				}
				System.out.println("1.修改途经点 2.修改目的地="+orderItems.getTjdOrmdd());
				User uu = userMapper.selectByPrimaryKey(ooi.getDirberId());//
				if (orderItems.getTjdOrmdd() != null && orderItems.getTjdOrmdd() == 1) {// 1 途经点  2目的地
					if (ooi.getDirberId() != 0) {
						FireBaseUtil.sendMessageAlertAndChangeAddress(uu.getUseEquipment(), "Rider added an extra stop");
						FireBaseUtil.postDataForFireBaseDataBase(uu.getId()+"", "{\"orderId\":" + orderItems.getId() + ",\"type\":1,\"status\":20}");//向firebase数据库添加数据
					}
				} else {
					if (ooi.getDirberId() != 0) {
						FireBaseUtil.sendMessageAlertAndChangeAddress(uu.getUseEquipment(), "Rider changed the destination");
						FireBaseUtil.postDataForFireBaseDataBase(uu.getId()+"", "{\"orderId\":" + orderItems.getId() + ",\"type\":1,\"status\":21}");
					}
				}
			}else{//保存
				//未支付记录
				int unpay=orderItemsMapper.getMyunPayment1(orderItems.getuId());
				if(unpay>0){
					return new ReturnData(800,LanguageUtils.returnLan(language, "unpay"));
				}
				
				if(jedis==null){
					 jedis = jedisPool.getResource();
				}
				List<CarCaculation> ccmlist1 =new ArrayList<>();
				List<CarCaculation> ccmlist =new ArrayList<>();
				String carcresult=jedis.get("carCaculation_carType"+orderItems.getCarType());
				if(StringTools.isEmpty(carcresult)){
					ccmlist1 = carCaculationMapper.getCarCaculation(map);// 计价规则
					JSONArray ja = JSONArray.fromObject(ccmlist1);
					String jlist=ja.toString();
					jedis.set("carCaculation_carType"+orderItems.getCarType(), jlist);
					if(ccmlist1.size()>0){
						ccmlist.add(ccmlist1.get(0));
					}
				}else{
					ccmlist1 = JSONArray.toList(JSONArray.fromObject(carcresult),CarCaculation.class);
					if(ccmlist1.size()>0){
						CarCaculation c=ccmlist1.get(0);
						ccmlist.add(c);
					}
				}
				if (ccmlist.size() > 0) { // 计算预估价
					CarCaculation carCaculation = ccmlist.get(0);
					orderItems.setMinimumFare(carCaculation.getMinimumFare().toString());	
				}
				if(orderItems.getEstimatePrice()!=null){//如果预估价小于最低消费 就使用最低消费
					if(orderItems.getEstimatePrice().doubleValue()-Double.parseDouble(orderItems.getMinimumFare())<=0){
						orderItems.setEstimatePrice(new BigDecimal(orderItems.getMinimumFare()));
					}
				}
			orderItems.setCreateTime(new Date());
			orderItems.setOrderNo(orderNo);
			orderItems.setName(u.getFirstName());
			orderItems.setTelephone(u.getTelephone());
			int num = orderItemsMapper.insertSelective(orderItems);
			if (num == 0) {
				code = 209;
				msg = LanguageUtils.returnLan(language, "new_orders_failed");
			}
			  userMapper.updateByPrimaryKeySelective(u);
			
			}
			/// 。。。。。。。。。。以上为支付、、、
			OrderItems oi1 = null;
			if (code == 200) {
				oi1 = orderItemsMapper.selectOrderByNo(orderNo);
			}
			return new ReturnData(oi1, code, msg);
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}finally {
			if(jedis!=null){
				jedis.close();
			}
		}
	}

	
	// 获取订单
	private String getOrderNo() {
		Date d = new Date();
		String timess = DateUtil.format(d, "yyyy-MM-dd");
		String str = orderItemsMapper.selectMaxOrderNo(timess);
		if (str == null) {
			str = "000" + 1;
		} else {
			Integer no = Integer.parseInt(str);
			if (no < 9) {
				str = "000" + (no + 1);
			} else if (no >= 9 && no < 99) {
				str = "00" + (no + 1);
			} else if (no >= 99 && no < 999) {
				str = "0" + (no + 1);
			} else {
				str = "" + (no + 1);
			}
		}
		String no = "FAB" + DateUtil.format(d, "yyyyMMdd") + str;
		return no;
	}

	//
	@Override
	public ReturnData valuationRules() {
		Map<String, Object> map = new HashMap<>();
		try {
			List<CarCaculation> ccmlist = carCaculationMapper.getCarCaculation(map);// 计价规则
			if (ccmlist.size() > 0) {
				return new ReturnData(ccmlist, 200, "success");
			}
			return new ReturnData(201, "fail");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}
	}

	@Override
	public ReturnData getMyBrank(Long uId) {
		Map<String, Object> map = new HashMap<>();
		map.put("uId", uId);
		List<UserBrank> ubList = userBrankMapper.getUserBrank(map);
		try {
			return new ReturnData(ubList, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}
	}

	// 用户端 司机列表 附近的车-附近半径5公里范围内的在线的并允许此服务的车辆【3分钟内可以接单、空闲】
	/**
	 * * 用户端 司机列表 附近的车-附近半径5公里范围内的在线的并允许此服务的车辆【3分钟内可以接单、空闲】
	 * 
	 * @param lng
	 *            经度
	 * @param lat
	 *            纬度
	 * @param cityName
	 *            城市名称
	 * @param distance
	 *            1 近到远 2 远到近
	 * @param appraise
	 *            评价 1 低 分数低到高 2 高 分数高到低
	 * @param singularNum
	 *            单数 1 高 2低
	 * @param carType
	 *            用车类型 1fab ONE 2fab 3fab PRO 3可以服务 1、2、3 ；2可以服务 1、2 ；1只能服务1
	 * @return
	 */
	@Override
	public ReturnData driverList(String lng, String lat, String cityName, Integer distance, Integer appraise,
			Integer singularNum, Integer pageNo, Integer pageSize, Integer carType) {
		Map<String, Object> map = new HashMap<>();
		if (!StringTools.isEmpty(cityName)) {
			map.put("cityName", cityName);
		}
		if (!RegexUtil.isNull(appraise)) {
			map.put("appraise", appraise);
		}
		if (RegexUtil.isNull(pageNo)) {
			pageNo = 1;
		}
		if (RegexUtil.isNull(pageSize)) {
			pageSize = 10;
		}
		try {
			List<CityRecord> list = cityRecordMapper.getList(map);// 查询服务于该城市的司机
			if (list.size() > 0) {
				map.put("cityId",  list.get(0).getId());
			}
			map.put("identity", 2);
			double lng2 = Double.parseDouble(lng);
			double lat2 = Double.parseDouble(lat);
			// map.put("serverStatus", 0);//司机服务状态 0空闲 1服务中  //默认给到6个司机
			PageHelper.startPage(0, 6);
			List<NearDriver> listDriver = userMapper.getNearDriverList(map);// 查询该城市的司机以及当前位置
			String[] strlist = null;
			// List<OrderItems> oiList=null;
			Integer[] orderStatus = { 2, 3, 4, 5, 6, 14 };// 未完成支付
			Date d = new Date();
			Iterator<NearDriver> it = listDriver.iterator();
			DecimalFormat    df   = new DecimalFormat("######0.00");   
			double s = 0.0;long ltime=0;
			// 查询所有司机
			while (it.hasNext()) { // 显示附近半径5公里范围内的在线的并允许此服务的车辆，和预订3分钟到达并目的地在5公里内的
				NearDriver nd = it.next();
				System.out.println("nd_id=" + nd.getId());
				Map<String, Object> map1 = new HashMap<>();
				map1.put("dirberId", nd.getId());
				Integer count = orderItemsMapper.getDriverOrderCount(map1);//
				nd.setCounts(count);// 接单量
				System.out.println("serverStatus=" + nd.getServerStatus());
				String serverType = nd.getOpenServerType();// 服务类型 1fab ONE 2fab
				System.out.println("serverType="+serverType);
				if(carType==1){//若是用户下单为fab ONE车型 则默认司机只提供一个座位
					nd.setSeatNum("1");
				}
				if (serverType.indexOf(String.valueOf(carType)) != -1) {// 是否能服务该车
					if (nd.getIs_last_order() != null && nd.getIs_last_order() == 2) {
						it.remove();
					}else if(nd.getNotOrder()!=null && nd.getNotOrder() == 2){//司机目前被禁止接单 由于未及时接单 收到十五分钟不能接单的惩罚
						it.remove();
					} else {
						if (nd.getServerStatus() == 1) {// 服务状态 0空闲 1服务中
							map.put("orderStatus", orderStatus);
							// map.put("dirberId", nd.getId());
							Long id = nd.getId();
							// oiList=
							// orderItemsMapper.getOrderItems(map);//查询司机是否有进行中的订单
							Long[] ss = { id };
							map.put("driverIds", ss);
							List<GisRecord> oiList = gisRecordMapper.selectByDriverId(map);
							if (oiList.size() > 0) {
								long diff = oiList.get(0).getTimes();// 结束服务的时间-当前时间
																		// 大于3分钟
																		// 不可接单
								 long diffMinutes = 0;
								if(diff!=0){
									diffMinutes=diff /  60;
								}
								if (diffMinutes > 10) {
									it.remove();
								} else {
									String position = nd.getPosition();// 司机目前的经纬度
									JSONArray jo1 = JSONArray.fromObject(position);
									if (jo1.size() > 0) {
										String position1 = (String) jo1.get(jo1.size() - 1);
										System.out.println("position1="+position1);
										strlist = position1.split(",");
										double lng1 = Double.parseDouble(strlist[0]);
										double lat1 = Double.parseDouble(strlist[1]);
										s = Distance.getDistance(lng1, lat1, lng2, lat2);
										String pos=strlist[1]+","+strlist[0];
										String pos1=lat2+","+lng2;
										Map<String,Object> fromTheTime=getGoogleTimes(pos,pos1);
//										ltime=Integer.parseInt(fromTheTime);
										ltime = (long) fromTheTime.get("timeValue");
										nd.setFromTheTime(fromTheTime.get("time").toString());
									}
//									String sss=df.format((s/1000));
//									nd.setApart();// 相距
									nd.setApart(Double.parseDouble(df.format((s/1000))));// 相距
									ltime =ltime/60;
									if (s > 5000||ltime>10) {// 附近半径5公里范围内的在线的并允许此服务的车辆
										it.remove();
									}
								}
							} else {
								String position = nd.getPosition();// 司机目前的经纬度
								JSONArray jo1 = JSONArray.fromObject(position);
								if (jo1.size() > 0) {
									String position1 = (String) jo1.get(jo1.size() - 1);
									System.out.println("position1="+position1);
									strlist = position1.split(",");
									double lng1 = Double.parseDouble(strlist[0]);
									double lat1 = Double.parseDouble(strlist[1]);
									s = Distance.getDistance(lng1, lat1, lng2, lat2);
									String pos=strlist[1]+","+strlist[0];
									String pos1=lat2+","+lng2;
									Map<String,Object> fromTheTime=getGoogleTimes(pos,pos1);
									ltime = (long) fromTheTime.get("timeValue");
									
									nd.setFromTheTime(fromTheTime.get("time").toString());
								}
								ltime =ltime/60;
								nd.setApart(Double.parseDouble(df.format((s/1000))));// 相距
								if (s > 5000||ltime>10) {// 附近半径5公里范围内的在线的并允许此服务的车辆
									it.remove();
								}
							}
						} else {
							String position = nd.getPosition();// 司机目前的经纬度
							JSONArray ja = JSONArray.fromObject(position);
							if (ja.size() > 0) {
								String positions = (String) ja.get(ja.size() - 1);
								if (positions != null) {
									strlist = positions.split(",");
									System.out.println("position="+positions);
									double lng1 = Double.parseDouble(strlist[0]);
									double lat1 = Double.parseDouble(strlist[1]);
									s = Distance.getDistance(lng1, lat1, lng2, lat2);
									System.out.println("Apart="+s);
									String pos=strlist[1]+","+strlist[0];
									String pos1=lat2+","+lng2;
									Map<String,Object> fromTheTime=getGoogleTimes(pos,pos1);
									ltime = (long) fromTheTime.get("timeValue");
									nd.setFromTheTime(fromTheTime.get("time").toString());
									System.out.println("时长=="+fromTheTime);
								}
							}
							ltime =ltime/60;
							nd.setApart(Double.parseDouble(df.format((s/1000))));// 相距
							if (s > 5000||ltime>10) {// 附近半径5公里范围内的在线的并允许此服务的车辆
								it.remove();
							}
						}
					}
				} else if (nd.getIs_last_order() != null && nd.getIs_last_order() == 2) {// 如果司机已经设置了是最后一单
					System.out.println("getIs_last_order="+nd.getIs_last_order());																	// 就不显示
					it.remove();
				} else if(nd.getNotOrder()!=null && nd.getNotOrder() == 2){//司机目前被禁止接单 由于未及时接单 收到十五分钟不能接单的惩罚
					System.out.println("getNotOrder="+nd.getNotOrder());		
					it.remove();
				} else { // 该司机不能服务于用户下的该订单
					it.remove();
					System.out.println("不服务该类型的车=");		
				}
				map1.remove("dirberId");
			}
			if (!RegexUtil.isNull(distance) && distance == 1) {// 距离远到近
				Collections.sort(listDriver, new Comparator<NearDriver>() {
					public int compare(NearDriver o1, NearDriver o2) {
						return o1.getApart().compareTo(o2.getApart());
					}
				});
			} else if(!RegexUtil.isNull(distance) && distance == 2){ // 近到远 降序
				Collections.sort(listDriver, new Comparator<NearDriver>() {
					public int compare(NearDriver o1, NearDriver o2) {
						return o2.getApart().compareTo(o1.getApart());
					}
				});
			}
			if (!RegexUtil.isNull(singularNum) && singularNum == 1) {// 单数 1 高
																		// 2低
				Collections.sort(listDriver, new Comparator<NearDriver>() {
					public int compare(NearDriver o1, NearDriver o2) {
						return o2.getCounts().compareTo(o1.getCounts());
					}
				});
			} else if (!RegexUtil.isNull(singularNum) && singularNum == 2){
				Collections.sort(listDriver, new Comparator<NearDriver>() {
					public int compare(NearDriver o1, NearDriver o2) {
						return o1.getCounts().compareTo(o2.getCounts());
					}
				});
			}
			return new ReturnData(listDriver, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}
	}

	@Override
	public ReturnData driverDetail(Long driverId) {
		Map<String, Object> map = new HashMap<>();
		Map<String, Object> map1 = new HashMap<>();
		Long[] l = { driverId };
		map.put("driverIds", l);
		map.put("byEvaluation", driverId);
		Jedis jedis=null; ConfigManager cm=null;Integer configTime=0;
		if(jedis==null){
			 jedis = jedisPool.getResource();
		}
		try {
			List<NearDriver> listDriver = userMapper.getNearDriverList1(map);// 查询司机信息
			NearDriver nd = null;
			if (listDriver.size() > 0) {
				nd = listDriver.get(0);
				map1.put("dirberId", driverId);
				Integer count = orderItemsMapper.getDriverOrderCount(map1);//
				nd.setCounts(count);
			}
			map.put("type", 2);
			PageHelper.startPage(0, 10);
			List<StarRemark> starRemark = starRemarkMapper.getStarRemarkList(map);
			map1.put("driver", nd);
			map1.put("starRemark", starRemark);// 频分
			String configManager=jedis.get("configManager");
			if(StringTools.isEmpty(configManager)){
				 cm = configManagerMapper.selectByPrimaryKey(1);
					JSONObject jo = JSONObject.fromObject(cm);
					jedis.set("configManager", jo.toString());
					configTime = cm.getOrderTime();
			}else{
				JSONObject jo = JSONObject.fromObject(configManager);
				cm = (ConfigManager) JSONObject.toBean(jo, ConfigManager.class);
				configTime = cm.getOrderTime();
			}
			map1.put("configTime", configTime);
			return new ReturnData(map1, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}finally {
			if(jedis!=null){
				jedis.close();
			}
		}
	}

	@Override
	public ReturnData isReceiptList(Long orderId, Long driverId, Integer language) {
		Map<String, Object> map = new HashMap<>();
		int code = 200;
		String msg = "success";
		boolean flag = true;
		map.put("dirberId", driverId);
		Integer[] orderStatus = { 1, 2, 3, 4, 5, 6, 14 };// 未完成支付
		map.put("orderStatus", orderStatus);
		try {
			List<OrderItems> list = orderItemsMapper.getOrderItems(map);// 查询司机在行程中的订单
			OrderItems oi = new OrderItems();
			if (list.size() > 0) {
				// 由于之前选择司机时 已过滤行程中 3分钟之后结束的才显示到列表中 故此处只查询司机是否有行程中的订单 有行程中订单
				// 司机默认接单
				Driver u = userMapper.getDriver(driverId);// 司机信息
				oi.setDirberId(driverId);
				oi.setStatus(3);// 预约成功(司机已确认)
				oi.setDriverPhone(u.getTelephone());
				oi.setDriverName(u.getName());
				oi.setId(orderId);
				int num = orderItemsMapper.updateByPrimaryKeySelective(oi);
				if (num == 0) {
					code = 201;
					msg = LanguageUtils.returnLan(language, "ordering_failure");
					flag = false;
				}
			} else {// 司机处于空闲状态
				code = 200;
				msg = LanguageUtils.returnLan(language, "no_trip_ordering");
				flag = true;
				// AuroraPush.pushTargetForDriver("driver"+driverId,
				// "你有一个新的订单");//给司机推送一个消息，通知他有新的订单了
			}
			return new ReturnData(flag, code, msg);
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}

	}

	/**
	 * 修改目的地、途经点 //修改之后需重新冻结预估价金额
	 * 
	 * @param orderId
	 * @param way_to_place
	 * @param way_to_place_jingwei
	 * @param arrived_location
	 * @param arrived_position
	 *            mileage //里程 开始地点到目的地的
	 * @param times
	 *            //计算结束时间 //开始地点到目的地的时长 trafficJamTime 堵车时长 language 语言
	 * @return
	 */
	@Override
	public ReturnData addWay(String json) {
		// 修改目的地与途经地 需冻结卡中金额 冻结之后修改行程
		OrderItems oi = StringTools.json2Obj(json, OrderItems.class);
		if (oi == null) {
			return new ReturnData(201, LanguageUtils.returnLan(2, "list_empty"));
		}
		double lat1 = 0.0;
		double lat2 = 0.0;
		double lng1 = 0.0;
		double lng2 = 0.0;
		double estimate = 0.0;
		Map<String, Object> map = new HashMap<>();
		// 堵车时长
		Integer the_traffic_time = Integer.parseInt(oi.getTrafficJamTime());
		// 正常时长
		Integer the_normal_time = oi.getTimes();
		// 堵车时长 比正常多出来的时长
		Integer traffic_time = the_traffic_time - the_normal_time;
		Jedis jedis=null;
		if(jedis==null){
			 jedis = jedisPool.getResource();
		}
		try {
			OrderItems oitems = orderItemsMapper.selectByPrimaryKey(oi.getOrderId());
			/////////////////// 冻结钱、、、、、、
			String departure_position = oitems.getDeparturePosition();// 上车地点的经纬度
			if (oi.getArrivedLocation() != null) {// 修改了目的地 此时重新计算预估价
				if(oitems.getDestinationCount()>0){
					return new ReturnData(306,LanguageUtils.returnLan(oi.getLanguage(), "change_of_destination"));
				}
				String arrived_position = oi.getArrivedPosition();// 结束地点的经纬度
				if (!StringTools.isEmpty(departure_position)) { // 开始地点的经纬度
					String[] strList = departure_position.split(",");
					lng1 = Double.parseDouble(strList[0]);// 经度
					lat1 = Double.parseDouble(strList[0]);// 纬度
				}
				if (!StringTools.isEmpty(arrived_position)) { // 目的地点的经纬度
					String[] strList = arrived_position.split(",");
					lng2 = Double.parseDouble(strList[0]);// 经度
					lat2 = Double.parseDouble(strList[0]);// 纬度
				}
				oitems.setDestinationCount(oitems.getDestinationCount()+1);
				// double miles= Distance.getDistance(lng1, lat1, lng2,
				// lat2);//开始地点与目的地的距离
				map.put("carType", oitems.getCarType());// 直接通过订单用车的类型 查询价格规则
//				List<CarCaculation> ccmlist = carCaculationMapper.getCarCaculation(map);// 计价规则
//				ooi.getCarType()
				List<CarCaculation> ccmlist1 =new ArrayList<>();
				List<CarCaculation> ccmlist =new ArrayList<>();
					String carcresult=jedis.get("carCaculation_carType"+oitems.getCarType());
					if(StringTools.isEmpty(carcresult)){
//						map.put("carType", oitems.getCarType());
						ccmlist1 = carCaculationMapper.getCarCaculation(map);// 计价规则
						JSONArray ja = JSONArray.fromObject(ccmlist1);
						String jlist=ja.toString();
						jedis.set("carCaculation_carType"+oitems.getCarType(), jlist);
						if(ccmlist1.size()>0){
							ccmlist.add(ccmlist1.get(0));
						}
					}else{
						ccmlist1 = JSONArray.toList(JSONArray.fromObject(carcresult),CarCaculation.class);
						if(ccmlist1.size()>0){
							CarCaculation c=ccmlist1.get(0);
							ccmlist.add(c);
						}
					}
				
				if (ccmlist.size() > 0) { // 计算预估价
					CarCaculation carCaculation = ccmlist.get(0);
					Double congestion_pricing = traffic_time * carCaculation.getTrafficJamPrice();// 堵车费
					Double how_fee = the_normal_time * carCaculation.getTimePrice();// 时长费
					Double mileage_fee = oi.getMileage() * carCaculation.getMileagePrice();// 里程费
					Double startPrice = carCaculation.getStartPrice();// 起步价
					estimate = startPrice + mileage_fee + how_fee + congestion_pricing;// 预估价
				}
				/*
				 * BigDecimal oldestimate=oitems.getEstimatePrice(); double
				 * oldep= oldestimate.doubleValue();
				 */// 原来的预估价
				EstimateFloat ef = estimateFloatMapper.getFloat();// 浮动区间
				Integer endFloat = ef.getEndFloat();
				double endf = (double) (endFloat / Double.valueOf(100));
				Double eestimatePrice = endf * estimate;
				DecimalFormat df = new DecimalFormat("######0.00");
				String endEstimatePrice = df.format(eestimatePrice + eestimatePrice);// 冻结时
																						// 冻结多的预估价金额
				// 是否需要取消上次冻结的，重新冻结 少的这部分
				double freezing_endEstimatePrice = Double.parseDouble(endEstimatePrice);
				if (freezing_endEstimatePrice > 0) {
					/////// 取消之前该用的的冻结金额，重新冻结预估价【freezing_endEstimatePrice】
				}
				
			}else{
				if(oi.getTujingdianCount()>0){
					return new ReturnData(306,LanguageUtils.returnLan(oi.getLanguage(), "change_of_via_point"));
				}
				oitems.setTujingdianCount(oitems.getTujingdianCount()+1);//途经点修改的次数+1
			}
			/////////////////// 冻结钱、、、、、、
			Calendar calendar = Calendar.getInstance();
			long millis = DateUtil.getMillis(oitems.getServiceStartTime()) + ((long) oi.getTimes()) * 3600 * 1000;
			calendar.setTimeInMillis(millis);
			Date dd = calendar.getTime();// 通过时长 计算结束时间
			oi.setServiceEndTime(dd);
			int num = orderItemsMapper.updateByPrimaryKeySelective(oitems);// 更新修改信息
			if(num==0){
				return new ReturnData(203,"fail");
			}
			return new ReturnData(200,"success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}finally {
			if(jedis!=null){
				jedis.close();
			}
		}
	}

	@Override
	public ReturnData getOrderDetail(Long orderId) {
		Map<String, Object> map = new HashMap<>();
		Map<String, Object> map3 = null;
		Map<String, Object> map1 = new HashMap<>();
		map1.put("orderId", orderId);
		Jedis jedis=null; ConfigManager cm=null;Integer configTime=0;
		if(jedis==null){
			 jedis = jedisPool.getResource();
		}
		try {
			OrderItems oiad = orderItemsMapper.selectByPrimaryKey(orderId);
//			OrderItemsAndDriver oiad = orderItemsMapper.getOrderDetail(map1);// 查询订单的星星
			if (oiad != null) {
				map.put("orderId", oiad.getId());
				List<OrderChargeDetail> ocd = orderChargeDetailMapper.getOrderChargeDetail(map);
				if(ocd.size()>0){
					map3=ocdObj(ocd.get(0));
					oiad.setOcd(map3);
				}
				if(!RegexUtil.isNull(oiad.getDirberId())){
					User u = userMapper.selectByPrimaryKey(oiad.getDirberId());
					map.put("dirberId", oiad.getDirberId());
					Integer count = orderItemsMapper.getDriverOrderCount(map);// 查询该司机的接单量
					u.setCounts(count.toString());
					oiad.setCounts(count.toString());// 接单量
					oiad.setDriver(u);
				}
				if(!RegexUtil.isNull(oiad.getCarId())){
					DriverAccessory da = driverAccessoryMapper.selectByPrimaryKey(oiad.getCarId());
					oiad.setDa(da);
				}
				map1.put("uId", oiad.getuId());
				List<OAStarRemark> li=starRemarkMapper.getStarRemarkOAList(map1);
				if(li.size()>0){
					oiad.setStar(li.get(0).getStar()+"");
					oiad.setRemark(li.get(0).getStar()+"");
				}
				String configManager=jedis.get("configManager");
				if(StringTools.isEmpty(configManager)){
					 cm = configManagerMapper.selectByPrimaryKey(1);
						JSONObject jo = JSONObject.fromObject(cm);
						jedis.set("configManager", jo.toString());
						configTime = cm.getOrderTime();
				}else{
					JSONObject jo = JSONObject.fromObject(configManager);
					cm = (ConfigManager) JSONObject.toBean(jo, ConfigManager.class);
					configTime = cm.getOrderTime();
				}
				oiad.setConfigTime(configTime);
			}
			return new ReturnData(oiad, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}finally {
			if(jedis!=null){
				jedis.close();
			}
		}

	}

	
	public ReturnData usercancelOrderCount(Long orderId){
		OrderItems oi = orderItemsMapper.selectByPrimaryKey(orderId);// 查询订单
		Date d = new Date(); boolean flag=false;int code=200;
		Map<String, Object> maps = new HashMap<>();
		maps.put("uId", oi.getuId());
		maps.put("date", DateUtil.format(d, "yyyy-MM-dd"));
		String count1=orderItemsMapper.getUserCancelledCount(maps);//当天该用户取消订单的次数
		int count=count1==null||count1==""?0:Integer.parseInt(count1);
		if(count<2){//用户取消次数超过两次 收取  取消费
			// 3分半以内不收费  3分半之后  总共收取用户的金额=预定费+取消费
			// 毫秒ms
			long diff = d.getTime() - oi.getUpTime().getTime();
			long diffMinutes = diff / 1000;// 获得当前时间距离下单时间  // 150S 3分半内取消订单不收取违约金,150秒可后台配置
/*			if (diffMinutes > 180) {
				flag=true; code=201;
			   }*/
			if(oi.getCarType()==4&&diffMinutes > 780){//如果用车类型是concierge
				flag=true; code=203;
		   }else if (diffMinutes >180){
			   flag=true; code=201;
		    }
		}else{
			flag=true;code=202;
		}
		return new ReturnData(flag, code, "");
	}
	
	/**
	 * 
	 */
	@Override
	public ReturnData cancelOrder(Long orderId, Integer language,String customer_ip,HttpServletRequest request) {
		Jedis jedis=null;
		if(jedis==null){
			jedis = jedisPool.getResource();
		}
		int code = 200;
		String msg = LanguageUtils.returnLan(language, "cancel_succeed");// 取消成功
		Map<String, Object> map = new HashMap<>();boolean flag=true;
		  //用户需支付的取消费      totalPrice    //取消费 司机所得 driverIncomecancelationFee   //fabcancelationFee =fab平台抽成     //fab能拿的
		Double totalPrice = 0.0;Double driverIncomecancelationFee=0.0;Double fabcancelationFee=0.0;Double bookingFee=0.0;Double fabcanComm=0.0;
		Double minimumFare=0.0;Double cancle =0.0;Map<String, Object> map1 = new HashMap<>();
		try {
			OrderItems oi = orderItemsMapper.selectByPrimaryKey(orderId);// 查询订单
			map.put("orderId", orderId);
			List<OrderCancel> list = orderCancelMapper.queryIsCanael(map);
			User u = userMapper.selectByPrimaryKey(oi.getDirberId());
			User user=userMapper.selectByPrimaryKey(oi.getuId()); 
			if (list.size() > 0) {
				code = 201;
				msg = LanguageUtils.returnLan(language, "cancel_fail_ybqx");// 订单已经被取消了
				return new ReturnData(code, msg);
			} else {
				if(oi.getStatus()==1){//订单状态为1  代表司机还没有接单 取消是不算做取消次数的
					oi.setStatus(16);//用户在 司机未接单时取消
					orderItemsMapper.updateByPrimaryKeySelective(oi);//
					punishment(u.getId());//司机取消惩罚
					FireBaseUtil.sendMessageAlertAndSoundCancel(u.getUseEquipment(), "Rider canceled the order");
					FireBaseUtil.postDataForFireBaseDataBase(u.getId()+"", "{\"orderId\":" + orderId + ",\"type\":1,\"status\":16}");
					return new ReturnData(200,LanguageUtils.returnLan(language, "cancel_fail_sijiweijiedanuserCancel"));
				}
				
				
				map1.put("carType", oi.getCarType());// 查询订单的用车类型计价规则
//				List<CarCaculation> ccmlist = carCaculationMapper.getCarCaculation(map1);// 计价规则
				List<CarCaculation> ccmlist1 =new ArrayList<>();
				List<CarCaculation> ccmlist =new ArrayList<>();
					String carcresult=jedis.get("carCaculation_carType"+oi.getCarType());
					if(StringTools.isEmpty(carcresult)){
						ccmlist1 = carCaculationMapper.getCarCaculation(map1);// 计价规则
						JSONArray ja = JSONArray.fromObject(ccmlist1);
						String jlist=ja.toString();
						jedis.set("carCaculation_carType"+oi.getCarType(), jlist);
						if(ccmlist1.size()>0){
							ccmlist.add(ccmlist1.get(0));
						}
					}else{
						ccmlist1 = JSONArray.toList(JSONArray.fromObject(carcresult),CarCaculation.class);
						if(ccmlist1.size()>0){
							CarCaculation c=ccmlist1.get(0);
							ccmlist.add(c);
						}
					}
					if (ccmlist.size() > 0) {
						 cancle = ccmlist.get(0).getCancelationFee();//取消费+预定费
						totalPrice = cancle+ccmlist.get(0).getBookingFee();fabcancelationFee=ccmlist.get(0).getCancelationFee()*ccmlist.get(0).getFabCommission();
						fabcanComm=fabcancelationFee-PinPayHttpUtils.formula(totalPrice);//取消费减去fab平台收取的 就是司机应该得的
						driverIncomecancelationFee=(ccmlist.get(0).getCancelationFee()-(fabcancelationFee));
						bookingFee =ccmlist.get(0).getBookingFee();
						minimumFare = ccmlist.get(0).getMinimumFare();
//						driverIncomecancelationFee =ccmlist.get(0).getCancelationFee()-fabcancelationFee;
					}
					Date d = new Date();
					Map<String, Object> maps = new HashMap<>();
					maps.put("uId", oi.getuId());
					maps.put("date", DateUtil.format(d, "yyyy-MM-dd"));
					String count1=orderItemsMapper.getUserCancelledCount(maps);//当天该用户取消订单的次数
					int count=count1==null||count1==""?0:Integer.parseInt(count1);
                   // 有司机接单 肯定会有司机 不然该订单跳转到的是司机列表
					System.out.println(maps+" 用户取消次数统计  count==="+count);
					if(count<2){//用户取消次数超过两次 收取  取消费
						// 3分半以内不收费  3分半之后  总共收取用户的金额=预定费+取消费
						// 毫秒ms
						long diff = d.getTime() - oi.getUpTime().getTime();
						long diffMinutes = diff / 1000;// 获得当前时间距离下单时间  // 150S 3分半内取消订单不收取违约金,150秒可后台配置
						if(oi.getCarType()==4&&diffMinutes <= 780){//如果用车类型是concierge
								totalPrice = 0.0;
								flag=false;
						}else if (diffMinutes <= 180){
								totalPrice = 0.0;flag=false;
						}
					}else{
						FireBaseUtil.sendMessageAlert(user.getUseEquipment(), "You have cancelled more than 2 times. Fab will charge you for the cancellation fee $"+totalPrice);
					}
			}
			OrderCancel orderCancel = new OrderCancel();
			orderCancel.setCreateTime(new Date());
			orderCancel.setOrderId(orderId.toString());
			orderCancel.setReason("Active cancellation");//用户主动取消
			orderCancel.setuId(oi.getuId());
			orderCancel.setType(2);// 1司机端取消 2用户端取消 3自动取消
			orderCancel.setDriverId(oi.getDirberId());// 司机id
			int n = orderCancelMapper.insertSelective(orderCancel);
			if (n == 0) {
				code = 206;
				msg = LanguageUtils.returnLan(language, "cancel_fail");
			} 
			
			Integer status = 10;
			int num =0;
			Integer amount=0;
			if (flag) {//支付取消费
			////支付取消费用   ////需同时向fab的卡中存入fabcancelationFee
				status = 11;
				UserBrank ub = userBrankMapper.selectByPrimaryKey(oi.getUbId());
				BigDecimal bd = new BigDecimal(totalPrice);
				oi.setTotalPrice(bd);
		      //////////用户支付 totalPrice1 金额  /////////
				amount=(int) (totalPrice*100);
		    	 String jrc=null; String jrc1=null;
		    	Map<String,Object> resut=getPinPaymentResult(amount,oi,user,customer_ip,ub);//支付
		    	  if(resut.get("code")!=null&&(int)resut.get("code")==201){//支付成功
		    		  ResponseCharges rc=(ResponseCharges) resut.get("obj");
		    		   jrc = JSONObject.fromObject(rc).toString();
		                ///////////////支付给fab平台的费用/////////////////
//			    		Double fab= PinPayHttpUtils.formula(totalPrice)-driverIncomecancelationFee;//总的费用-司机的收入  最终剩下的就是平台应该得到了
			    		if(fabcanComm>0){
//			    			ConfigManager cm=configManagerMapper.selectByPrimaryKey(1);//查询配置信息
			    			ConfigManager cm=null;
			    			String configManager=jedis.get("configManager");
			    			if(StringTools.isEmpty(configManager)){
			    				 cm = configManagerMapper.selectByPrimaryKey(1);
			    					JSONObject jo = JSONObject.fromObject(cm);
			    					jedis.set("configManager", jo.toString());
			    			}else{
			    				JSONObject jo = JSONObject.fromObject(configManager);
			    				cm = (ConfigManager) JSONObject.toBean(jo, ConfigManager.class);
			    			}
			    			Map<String, String> fabMap=new HashMap<>();
			    			fabMap.put("amount", (fabcanComm*100)+"");//需要支付的金额
			    			fabMap.put("currency", "AUD");
			    			fabMap.put("description", user.getFirstName()+" Cancel the order platform for $"+fabcanComm);
			    			fabMap.put("recipient", cm.getFab_token());//收件人凭证
					    	Map<String,Object> fabresult=  PinPayHttpUtils.sendPinPayCreateTransfersPost(fabMap);
					    	 if(fabresult.get("code")!=null&&(int)fabresult.get("code")==201){//支付成功
					    		 ResponseTransfers rc1=(ResponseTransfers) fabresult.get("obj");
					    		   jrc1 = JSONObject.fromObject(rc1).toString();
					   		}else if(fabresult.get("code")!=null&&(int)fabresult.get("code")==422){
					   			ErrorResponseCard rc1=(ErrorResponseCard) fabresult.get("obj");
					   			String error="";
					   			if(rc!=null){
					   				List<ErrorMessage> liMessage=JSONArray.toList(JSONArray.fromObject(rc1.getMessages()), ErrorMessage.class);
					                for(ErrorMessage ee:liMessage){
					              	  error+=ee.getMessage()+" ; "; 
					                }
					   			}
					   			code=900;
					   			jrc1 =  JSONObject.fromObject(rc1).toString();;msg=error;
					   		}else if(fabresult.get("code")!=null&&(int)fabresult.get("code")==400){
					   			ErrorResponse400 rc1=(ErrorResponse400) fabresult.get("obj");
					   			jrc1 = JSONObject.fromObject(rc1).toString();
					   			code=900;msg=rc1.getError_description();
							}
					    	 PinpayRecord fabppr = new PinpayRecord(oi.getId(),jrc1,(int)fabresult.get("code"),new Date(),3);//支付记录
				    		 pinpayRecordMapper.insertSelective(fabppr);
			    		}  
			    		status = 12;
		   		}else if(resut.get("code")!=null&&(int)resut.get("code")==422){
		   			ErrorResponseCard rc=(ErrorResponseCard) resut.get("obj");
		   			String error="";
		   			if(rc!=null){
		   				List<ErrorMessage> liMessage=JSONArray.toList(JSONArray.fromObject(rc.getMessages()), ErrorMessage.class);
		                for(ErrorMessage ee:liMessage){
		              	  error+=ee.getMessage()+" ; "; 
		                }
		   			}
		   			jrc =  JSONObject.fromObject(rc).toString();;msg=error;
		   			ReturnData rd=ChooseDeductions(oi, u, oi.getuId(), oi.getUbId(), amount, customer_ip);//扣取没有拿到的钱
			   		code=rd.getCode();
			   			status = 11;
		   		}else if(resut.get("code")!=null&&(int)resut.get("code")==400){
		   			ErrorResponse400 rc=(ErrorResponse400) resut.get("obj");
		   			jrc = JSONObject.fromObject(rc).toString();
		   			ReturnData rd=ChooseDeductions(oi, u, oi.getuId(), oi.getUbId(), amount, customer_ip);//扣取没有拿到的钱
			   		code=rd.getCode();
			   		status = 11;
//		   			code=900;msg=rc.getError_description();
				}
		    	  PinpayRecord ppr = new PinpayRecord(oi.getId(),jrc,(int)resut.get("code"),new Date(),1);//支付记录
	    		  pinpayRecordMapper.insertSelective(ppr);
				oi.setIsDeleted(1);
				oi.setStatus(status);
				 num = orderItemsMapper.updateByPrimaryKeySelective(oi);
				if(u!=null&&u.getConsumetotal()!=null){
					u.setConsumetotal(u.getConsumetotal()+driverIncomecancelationFee);//记录周末给司机转账的金额
					userMapper.updateByPrimaryKeySelective(u);
				}
				OrderChargeDetail ocd = new OrderChargeDetail();
				ocd.setBookingFee(bookingFee);
				ocd.setTotalFee(totalPrice);//取消费+预定费
				ocd.setDriverId(oi.getDirberId());
				ocd.setCalType(oi.getCarType());
				ocd.setCreateTime(new Date());
				ocd.setCancelFee(cancle);
				ocd.setOrderDriverSettlement(driverIncomecancelationFee);
				ocd.setOrderFabCommissions(0.0);
				if(fabcanComm>0){
					ocd.setOrderFabCommissions(fabcanComm);
				}
				ocd.setMinimumFare(minimumFare);
				ocd.setTotalMoney(totalPrice);
				ocd.setTotals(totalPrice);
				ocd.setOrderId(oi.getId()+"");
				ocd.setuId(oi.getuId());
				orderChargeDetailMapper.insertSelective(ocd);//保存记录
			} else {
				oi.setTotalPrice(new BigDecimal(0.0));
				oi.setStatus(status);
				oi.setIsDeleted(1);
				 num = orderItemsMapper.updateByPrimaryKeySelective(oi);
			}
		/*	if (num == 0) {
				return new ReturnData(202, LanguageUtils.returnLan(language, "cancel_order_fail"));
			}else {}*/
			//给司机推送
			FireBaseUtil.sendMessageAlertAndSoundCancel(u.getUseEquipment(), "Rider canceled the order");
			FireBaseUtil.postDataForFireBaseDataBase(u.getId()+"", "{\"orderId\":" + orderId + ",\"type\":1,\"status\":"+status+"}");
			if(oi.getCarId()==null){//没有司机接单
				punishment(u.getId());//司机取消惩罚
			}
			DriverAccessory da = new DriverAccessory();
			da.setId(oi.getCarId());
			Map<String, Object> dmap = new HashMap<>();
			dmap.put("dirberId", oi.getDirberId());// 查询我的订单
			Integer[] orderStatus = {  2, 3, 4, 5 };// 未完成支付
			dmap.put("orderStatus", orderStatus);
			List<OrderItems> dlist = orderItemsMapper.getOrderItems(dmap);
			//如果该司机有服务中的订单  则不修改用车在用状态
			if(oi.getCarId()!=null&&oi.getCarId()!=0&&dlist.size()==0){ //司机接单了的订单
				da.setServerStatus(0);//司机的车辆状态为空闲
				int damn=driverAccessoryMapper.updateByPrimaryKeySelective(da);//更新司机的车
				if(damn == 0){
					return new ReturnData(302,LanguageUtils.returnLan(language, "update_car_failed"));
				}
			}else {
				// 添加消息记录
				UserMessage um = new UserMessage();
				um.setCreateTime(new Date());
				um.setmContext("Rider take the initiative to cancel");
				um.setmName("Rider take the initiative to cancel");
				um.setmSummary("Rider take the initiative to cancel");
				um.setName(oi.getName());
				um.setType(1);
				um.setuId(oi.getuId());
				int n1 = userMessageMapper.insertSelective(um);
				if (n1 == 0) {
					code = 220;
					msg = LanguageUtils.returnLan(language, "cancel_fail");
				}
			}
			return new ReturnData(code, msg);
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}finally {
			if(jedis!=null){
				jedis.close();
			}
		}
	}
//司机取消惩罚
private void punishment(Long driverId){
	Map<String,Object> maps = new HashMap<>();//解除司机的惩罚
	maps.put("difference", 1);//区别  1用户端 用户确认订车  司机为空闲状态没有接单 15分钟内不能接单  2.司机取消超过多少次被惩罚
	List<UserConfirmTheOrdering> lists=userConfirmTheOrderingMapper.getUserConfirmTheOrdering(maps);
	for(UserConfirmTheOrdering ucto:lists){
		if(ucto.getDifference()==1){
			userConfirmTheOrderingMapper.deleteByPrimaryKey(ucto.getId());
			FireBaseUtil.postDataForFireBaseDataBase(driverId+"", "{\"type\":3,\"orderId\":0,\"status\":2}");
		}
	}
	User u = new User();
	u.setId(driverId);
	u.setNotOrder(1);
	userMapper.updateByPrimaryKeySelective(u);
}

	@Override
	public ReturnData getCouponsIdQueryOrder(Long couponsId) {
		Map<String, Object> map1 = new HashMap<>();
		Map<String, Object> map = new HashMap<>();
		map1.put("couponId", couponsId);
		try {
			OrderItemsAndDriver oiad = orderItemsMapper.getOrderDetail(map1);// 查询订单的
			if (oiad != null) {
				map.put("dirberId", oiad.getDirberId());
				Integer count = orderItemsMapper.getDriverOrderCount(map);// 查询该司机的接单量
				oiad.setCounts(count.toString());// 接单量
			}
			return new ReturnData(oiad, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}
	}

	@Override
	public ReturnData getOrderStroke(Long orderId) {
		try {
			List<StrokeRecord> list = strokeRecordMapper.selectRecordByOrderId(orderId);
			return new ReturnData(list, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}
	}

	@Override
	public ReturnData getMyItinerary(Long uId, Integer pageNo, Integer pageSize) {
		Map<String, Object> map = new HashMap<>();
		Map<String, Object> map1 = new HashMap<>();
		if (RegexUtil.isNull(pageNo)) {
			pageNo = 1;
		}
		if (RegexUtil.isNull(pageSize)) {
			pageSize = 10;
		}
		map.put("uId", uId);
		Integer[] ywc = { 8, 9, 10, 12, 13 };
		Integer[] wwc = {  2, 3, 4, 5, 6, 7, 11, 15,14 };

		map.put("orderStatus", ywc);// 已完成
		map.put("isShow", 1);
		try {
			PageHelper.startPage(pageNo, pageSize);
			List<OrderItems> list = orderItemsMapper.getOrderItems(map);
			map1.put("completed", list);
			map.remove("orderStatus");// 未完成
			map.put("orderStatus", wwc);
			PageHelper.startPage(pageNo, pageSize);
			List<OrderItems> list1 = orderItemsMapper.getOrderItems(map);
			map1.put("noCompleted", list1);
			return new ReturnData(map1, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}
	}

	@Override
	public ReturnData changeOrderStatus(Long orderId, Integer status, Integer driverId, Integer carType,
			Integer language, Long carId) {
		if (orderId == null) {
			return new ReturnData(301, "The order ID cannot be empty.");
		} else if (driverId == null) {
			return new ReturnData(302, "Driver ID cannot be empty.");
		} else if (status == null) {
			return new ReturnData(305, "The state cannot be empty.");
		} else if (language == null) {
			return new ReturnData(306, "Language cannot be empty.");
		}
		Integer time = 0;
		Jedis jedis = null;
		if(jedis==null){
			jedis =jedisPool.getResource();
		}
		try {
			OrderItems ooi = orderItemsMapper.selectByPrimaryKey(orderId);// 通过订单id查询订单
			if(ooi.getStatus()==10||ooi.getStatus()==11||ooi.getStatus()==12){//用户取消了 该订单司机不能接单
				return new ReturnData(900,"The order has been cancelled and you can't take the order.");
			}
			Map<String,Object> map = new HashMap<>();
			User u = userMapper.selectByPrimaryKey((long) driverId);
			User u1 = userMapper.selectByPrimaryKey(ooi.getuId());
			String context = "";
			
			if (status.equals(2)) {
				String unfinishedCount=orderItemsMapper.driverUnfinished((long)driverId);//司机是否有未完成的订单
				if(!StringTools.isEmpty(unfinishedCount)&&Integer.parseInt(unfinishedCount)>0){
					return new ReturnData(280, "The driver has been booked by other passengers.");
				}
				if (ooi.getDirberId() != null && ooi.getDirberId() != 0 && ooi.getStatus()==2) {//订单已经选择别的司机 如果别的司机把订单状态改为 2 别的司机接单了
					return new ReturnData(230, "Passengers have chosen other drivers.");
				}
				ooi.setStatus(status);
				/*DriverAccessory dcar=driverAccessoryMapper.selectByPrimaryKey(carId);//该车是否在使用
				if(dcar.getServerStatus()==1){//如果这个车的服务状态为服务中，该车目前就不能再接单
					return new ReturnData(240, "You have an order in the service now. You can't take the order again.");
				}*/
//				List<ConfigManager> cm = configManagerMapper.getList();
//				if (cm.size() > 0) {
//					time = cm.get(0).getOrderTime();
//				}
				String configManager=jedis.get("configManager");
				ConfigManager cm=null;
				if(StringTools.isEmpty(configManager)){
					 cm = configManagerMapper.selectByPrimaryKey(1);
						JSONObject jo = JSONObject.fromObject(cm);
						jedis.set("ConfigManager", jo.toString());
						time = cm.getOrderTime();
				}else{
					JSONObject jo = JSONObject.fromObject(configManager);
					cm = (ConfigManager) JSONObject.toBean(jo, ConfigManager.class);
					time = cm.getOrderTime();
				}
				Date d = new Date();
				long times = d.getTime() - ooi.getUpTime().getTime();
				int sjc = (int) (times / 1000);// 秒为单位
				if (sjc > time) {
					return new ReturnData(209, LanguageUtils.returnLan(language, "order_timeout"));
				}
				ooi.setStatus(2);
				map.put("driverId", driverId);
				List<UserConfirmTheOrdering> list=userConfirmTheOrderingMapper.getUserConfirmTheOrdering(map);
				if(list.size()>0){
					for(UserConfirmTheOrdering uc:list){
		    			u.setNotOrder(1);//司机这时  可以接单  
		    			userMapper.updateByPrimaryKeySelective(u);//更新司机这是不能出现在乘客的司机列表中
		    			userConfirmTheOrderingMapper.deleteByPrimaryKey(uc.getId()); //删除临时表中的记录 司机接单了  无需惩罚
		    			FireBaseUtil.postDataForFireBaseDataBase(u.getId()+"", "{\"type\":3,\"orderId\":0,\"status\":2}");
					}
				}
				if(carId!=null){
					DriverAccessory da=driverAccessoryMapper.selectByPrimaryKey(carId);
					ooi.setCarNum(da.getLicensePlate());//车牌号
				}
				ooi.setDriverPhone(u.getTelephone());
				ooi.setDriverName(u.getFirstName());
				if(ooi.getCarType()==4&&!StringTools.isEmpty(ooi.getUserAMessage())){//concierge 车型司机接单时  需要向司机发送用户下单留言的内容
					userService.sendSMS(u.getTelephone(), 10, ooi.getUserAMessage());
				}
				FireBaseUtil.sendMessageAlert(u1.getUseEquipment(), "Your fab ride is arriving; please meet at the pickup point.");
				FireBaseUtil.postDataForFireBaseDataBase(u1.getId()+"", "{\"orderId\":" + orderId + ",\"type\":1,\"status\":2}");
//				SendPushNotification.sendMessageAlertUser(u1.getUseEquipment(), "Your fab ride is arriving; please meet at the pickup point.");
//				SendPushNotification.sendMessageSilentUser(u1.getUseEquipment(), "{\"orderId\":" + orderId + ",\"type\":1,\"status\":2}", u1.getAuroraAlias());
//				AuroraPush.pushTargetForUser(u1.getUseEquipment(),
//						"{\"orderId\":" + orderId + ",\"type\":1,\"status\":2}", u1.getAuroraAlias());
//				AuroraPush.pushTargetAlertForUser(u1.getUseEquipment(), "Your fab ride is arriving; please meet at the pickup point.", u1.getAuroraAlias());
				context = "Your fab ride is arriving; please meet at the pickup point.";
			} else if (status.equals(3)) {// 已出发去接乘客
				ooi.setStatus(3);
				FireBaseUtil.sendMessageAlert(u1.getUseEquipment(), "Your fab ride is on the way");
				FireBaseUtil.postDataForFireBaseDataBase(u1.getId()+"", "{\"orderId\":" + orderId + ",\"type\":1,\"status\":3}");
//				SendPushNotification.sendMessageAlertUser(u1.getUseEquipment(), "Your fab ride is on the way");// 通知
//				SendPushNotification.sendMessageSilentUser(u1.getUseEquipment(), "{\"orderId\":" + orderId + ",\"type\":1,\"status\":3}", u1.getAuroraAlias());
//				AuroraPush.pushTargetForUser(u1.getUseEquipment(), "{\"orderId\":" + orderId + ",\"type\":1,\"status\":3}",
//						u1.getAuroraAlias());
//				AuroraPush.pushTargetAlertForUser(u1.getUseEquipment(), "Your fab ride is on the way", u1.getAuroraAlias());// 通知
				context = "Your fab ride is on the way";
			} else if (status.equals(4)) {// 已到达上车地点
				ooi.setStatus(4);
				ooi.setDestinationTime(new Date());//司机到达乘客上车地点的时间
				FireBaseUtil.sendMessageAlert(u1.getUseEquipment(), "Your fab ride has arrived at pickup point.");
				FireBaseUtil.postDataForFireBaseDataBase(u1.getId()+"", "{\"orderId\":" + orderId + ",\"type\":1,\"status\":4}");
//				SendPushNotification.sendMessageAlertUser(u1.getUseEquipment(), "Your fab ride has arrived at pickup point.");
//				SendPushNotification.sendMessageSilentUser(u1.getUseEquipment(), "{\"orderId\":" + orderId + ",\"type\":1,\"status\":4}",u1.getAuroraAlias());
//				AuroraPush.pushTargetForUser(u1.getUseEquipment(), "{\"orderId\":" + orderId + ",\"type\":1,\"status\":4}",
//						u1.getAuroraAlias());
//				AuroraPush.pushTargetAlertForUser(u1.getUseEquipment(), "Your fab ride has arrived at pickup point.", u1.getAuroraAlias());
				context = "Your fab ride has arrived at pickup point.";
				/*DriverStartServer ass=driverStartServerMapper.queryByOrderId(ooi.getId());
				Date d = new Date();
				if(ass==null){
					ass = new DriverStartServer();//临时表  便于遍历  10分钟内取消
					ass.setDriverId(ooi.getDirberId());
					ass.setCreateTime(d);
					ass.setOrderId(ooi.getId());
					driverStartServerMapper.insertSelective(ass);//保存开始服务
				}*/
			} else if (status.equals(5)) {// 乘客上车开始行程
				ooi.setStatus(5);
				Date d = new Date();
				ooi.setServiceStartTime(d);
				FireBaseUtil.postDataForFireBaseDataBase(u1.getId()+"", "{\"orderId\":" + orderId + ",\"type\":1,\"status\":5}");
				// 更新订单的信息
				/*DriverStartServer ass=driverStartServerMapper.queryByOrderId(ooi.getId());
				if(ass!=null){
					driverStartServerMapper.deleteByPrimaryKey(ass.getId());//删除
				}*/
			} else if (status.equals(7)) {// 司机结束服务，乘客待付款
				ooi.setStatus(7);
				ooi.setServiceEndTime(new Date());
				Long[] l = { ooi.getDirberId() };
				map.put("driverIds", l);
				List<GisRecord> list = gisRecordMapper.selectByDriverId(map);
				if (list.size() > 0) {
					for (GisRecord gr : list) {
						gr.setTimes(0);// 时长 
						gr.setMileage("0");// 里程
					}
				}
				FireBaseUtil.postDataForFireBaseDataBase(u1.getId()+"", "{\"orderId\":" + orderId + ",\"type\":1,\"status\":7}");
			}
			// ooi.setCarType(carType);
			ooi.setCarId(carId);
			ooi.setDirberId((long) driverId);
			int num = orderItemsMapper.updateByPrimaryKeySelective(ooi);// 更新订单状态
			if (num == 0) {
				return new ReturnData(201, LanguageUtils.returnLan(language, "fail_order_update"));
			}
			if (!StringTools.isEmpty(context)) {
				UserMessage um = new UserMessage();
				um.setCreateTime(new Date());
				um.setmContext(context);
				um.setmSummary(context);
				um.setName(context);
				um.setType(1);
				um.setuId(ooi.getuId());
				userMessageMapper.insertSelective(um);
			}
			List<DriverAccessory> l = driverAccessoryMapper.getUserCars(Long.parseLong(driverId.toString()));
			for (DriverAccessory da : l) {
				Long id = da.getId();
				if(!RegexUtil.isNull(carId)){//若
					if (id==carId) {
						da.setIsUse(1);// 今日是否在用 1正在使用 2未用
					} else {
						da.setIsUse(2);// 今日是否在用 1正在使用 2未用
					}
				}
				if (status.equals(2)) {
					da.setServerStatus(1);
				} else if (status.equals(7)) {// 司机结束服务 更新司机状态为空闲
//					da.setServerStatus(0);
					Map<String, Object> dmap = new HashMap<>();
					dmap.put("dirberId", ooi.getDirberId());// 查询我的订单
					Integer[] orderStatus = {  2, 3, 4, 5,7 };// 未完成支付
					dmap.put("orderStatus", orderStatus);
					List<OrderItems> dlist = orderItemsMapper.getOrderItems(dmap);
					//如果该司机有服务中的订单  则不修改用车在用状态
					if(dlist.size()==0){ 
						da.setServerStatus(0);//司机的车辆状态为空闲
					}
				}
				int n = driverAccessoryMapper.updateByPrimaryKeySelective(da);// 更新司机的状态、
				if (n == 0) {
					return new ReturnData(201, LanguageUtils.returnLan(language, "driver_update_failed"));
				}
			}
			return new ReturnData(200, LanguageUtils.returnLan(language, "successful_order_update"));
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}finally {
			if(jedis!=null){
				jedis.close();
			}
		}
	}
	
	public  String readTxtFile(Long orderId,Integer status,HttpServletRequest request){
        String read;
        List<String> readStr1=null;
        String readStr ="";
        FileReader  fileread;int num=0;
        String realPath =  request.getSession().getServletContext().getRealPath("/");
        String path2 = realPath.substring(0,realPath.lastIndexOf(System.getProperty("file.separator")));
        String p = realPath.substring(0, (path2.lastIndexOf(System.getProperty("file.separator"))))+System.getProperty("file.separator")+"file"+System.getProperty("file.separator")+"FABposition";
       
		 File filename = new File(p, orderId+".txt");  
		 if(!filename.exists()){
			 return readStr;
		 }
        try {
        	
//           if(status<8){
//        	   readStr = jedisClient.hget("order", orderId+"");
//           }else{
//        	readStr1=new ArrayList<>();
        	   fileread = new FileReader(filename);
               BufferedReader bufread = new BufferedReader(fileread);
               try {
                   while ((read = bufread.readLine()) != null) {
                   	readStr += read+ "\r\n";
//                	   readStr.add(read);
                   }
               } catch (IOException e) {
            	   
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   return readStr;
               }
//               readStr1.add(readStr);
//               readStr1 = readStr.toString();
//           }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return readStr;
        }
        System.out.println("文件内容是:"+ "\r\n" + readStr);
        JSONArray ja=JSONArray.fromObject(readStr);
         readStr1 = (List<String>) JSONArray.toList(ja, String.class);
        List<String> l1=new ArrayList<>();
        if(readStr1.size()>2){
        	if(readStr1.size()>23){
        		l1.add(readStr1.get(0));
        		int n=readStr1.size()/23;
        		for(int i=0;i<readStr1.size();i++){
        			if(i%(n+1)==0){
        				l1.add(readStr1.get(i));
        			}
        		}
        		l1.add(readStr1.get(readStr1.size()-1));
        	}else{
        		String ss="";
        		for(String s:readStr1){
    				ss+=s+",";
    			}
        		if(ss.length()>1){
        			ss = ss.substring(0, ss.length()-1);
        		}
         	l1.add(ss);
        	}
        }
        return JSONArray.fromObject(l1).toString();
    }

	// 司机取消订单 东西太多，无法上车的理由将不收取乘客费用，但需要乘客确认 //司机取消订单不收乘客的费用
	@Override
	public ReturnData driverCancelOrder(Long orderId, String reason, Integer language, Long driverId,String customer_ip) {
		int code = 200;
		String msg = LanguageUtils.returnLan(language, "cancel_succeed");// 取消成功
		Map<String, Object> map = new HashMap<>();
		map.put("orderId", orderId);// 查询该订单是否被取消了 用户或者司机取消之后 该订单都不能被再次取消了
		map.put("dirberId", driverId);
		map.put("createDate", DateUtil.formatDate(new Date()));
		BigDecimal bd = null;
		int driver_cancels=0;//司机取消的次数
		int bantime=0;//禁止多少分钟
		  //用户需支付的取消费      totalPrice    //取消费 司机所得 driverIncomecancelationFee   //fabcancelationFee =fab平台抽成
		Double totalPrice = 0.0;Double driverIncomecancelationFee=0.0;Double fabcancelationFee=0.0;Double bookingFee=0.0;Double fabcanComm=0.0;Double minimumFare=0.0;
		Double cancle=0.0; 
		Jedis jedis=null;
			if(jedis==null){
				jedis = jedisPool.getResource();
			}
			Integer status=null;
		try {
			OrderItems ooi = orderItemsMapper.selectByPrimaryKey(orderId);// 通过订单id查询订单  // 获取当前订单的状态
			User u = userMapper.selectByPrimaryKey(driverId);// 司机信息
			User user = userMapper.selectByPrimaryKey(ooi.getuId());// 司机信息
			List<OrderCancel> cancellist=orderCancelMapper.queryIsCanael(map);
			if(cancellist.size()>0){
				return new ReturnData(600,  LanguageUtils.returnLan(language, "cancel_fail_ybqx"));
			}
			
			map.remove("orderId");
			String counts1=orderItemsMapper.driversCancelledNum(map);//查询该订单是否被取消了 用户或者司机取消之后 该订单都不能被再次取消了
			
			//司机当日取消订单的次数
//			ConfigManager cm=configManagerMapper.selectByPrimaryKey(1);//查询配置信息
			ConfigManager cm=null;
			String configManager=jedis.get("configManager");
			if(StringTools.isEmpty(configManager)){
				 cm = configManagerMapper.selectByPrimaryKey(1);
					JSONObject jo = JSONObject.fromObject(cm);
					jedis.set("configManager", jo.toString());
			}else{
				JSONObject jo = JSONObject.fromObject(configManager);
				cm = (ConfigManager) JSONObject.toBean(jo, ConfigManager.class);
			}
			int counts =counts1==null||counts1==""?0:Integer.parseInt(counts1);
 			if(cm!=null){
 				driver_cancels=cm.getDriverCancels();
 				bantime = cm.getBantime();
			}
            	if(counts>=driver_cancels){//取消推送的信息
            		UserConfirmTheOrdering uco = new UserConfirmTheOrdering();
            		Date d=new Date();
            		uco.setCreateTime(d);
            		uco.setDifference(2);//
            		uco.setDriverId(ooi.getDirberId());
            		uco.setOrderId(ooi.getId());
            		userConfirmTheOrderingMapper.insertSelective(uco);//保存记录
            		FireBaseUtil.sendMessageAlert(u.getUseEquipment(), cm.getDriverCancelsSendContent());
            		FireBaseUtil.postDataForFireBaseDataBase(u.getId()+"", "{\"type\":8,\"status\":1,\"orderId\":0,\"time\":"+d.getTime()+",\"time_length\":"+bantime+"}");
            	}	
            	punishment(u.getId());//司机取消惩罚
            	
            	OrderCancel orderCancel = new OrderCancel();
				orderCancel.setCreateTime(new Date());
				orderCancel.setOrderId(orderId.toString());
				orderCancel.setReason(reason);
				orderCancel.setuId(ooi.getuId());
				orderCancel.setDriverId(driverId);
				orderCancel.setType(1);// 1司机端取消 2用户端取消 3自动取消
				int num = orderCancelMapper.insertSelective(orderCancel);
				if (num == 0) {
					code = 203;
					msg = LanguageUtils.returnLan(language, "cancel_fail");
				}else{
					//setDestinationTime  司机在去接乘客的路上 司机取消 没有任何费用
	            	if(ooi.getDestinationTime()!=null){//司机已经到达乘车上传的地点
	            	 long time=	new Date().getTime()-ooi.getDestinationTime().getTime();
					long diffMinutes = time / 1000;// 获得当前时间距离下单时间  // 150S 3分半内取消订单不收取违约金,150秒可后台配置
					if (ooi.getCarType()==4&&diffMinutes <= 780) {
						ooi.setStatus(10);// 10已取消(不收	费)
	        			ooi.setPayStatus(1);// 支付状态 0未支付 1已支付
	        			status=10;
	        			bd = new BigDecimal(0.0);
					   }else if(diffMinutes <= 180){
						    ooi.setStatus(10);// 10已取消(不收费)
		        			ooi.setPayStatus(1);// 支付状态 0未支付 1已支付
		        			status=10;
		        			bd = new BigDecimal(0.0);
					   }else{
						   bd = new BigDecimal(0.0);
							Map<String, Object> map1 = new HashMap<>();
							map1.put("carType", ooi.getCarType());// 查询订单的用车类型计价规则
							List<CarCaculation> ccmlist1 =new ArrayList<>();
						   List<CarCaculation> ccmlist =new ArrayList<>();
							String carcresult=jedis.get("carCaculation_carType"+ooi.getCarType());
							if(StringTools.isEmpty(carcresult)){
								ccmlist1 = carCaculationMapper.getCarCaculation(map1);// 计价规则
								JSONArray ja = JSONArray.fromObject(ccmlist1);
								String jlist=ja.toString();
								jedis.set("carCaculation_carType"+ooi.getCarType(), jlist);
								if(ccmlist1.size()>0){
									ccmlist.add(ccmlist1.get(0));
								}
							}else{
								ccmlist1 = JSONArray.toList(JSONArray.fromObject(carcresult),CarCaculation.class);
								if(ccmlist1.size()>0){
									CarCaculation c=ccmlist1.get(0);
									ccmlist.add(c);
								}
							}
							if (ccmlist.size() > 0) {
								 cancle = ccmlist.get(0).getCancelationFee();//取消费+预定费
								totalPrice = cancle+ccmlist.get(0).getBookingFee();fabcancelationFee=ccmlist.get(0).getCancelationFee()*ccmlist.get(0).getFabCommission();
								fabcanComm=fabcancelationFee-PinPayHttpUtils.formula(totalPrice);//取消费减去fab平台收取的 就是司机应该得的
								driverIncomecancelationFee=(ccmlist.get(0).getCancelationFee()-(fabcancelationFee));
								bookingFee =ccmlist.get(0).getBookingFee();
								minimumFare = ccmlist.get(0).getMinimumFare();
							}
							////////////////支付////////////////////
							//支付totalPrice费用
							Integer amount=0;
							if(totalPrice>1){
								UserBrank ub = userBrankMapper.selectByPrimaryKey(ooi.getUbId());//冻结预估价的卡
						      //////////用户支付 totalPrice1 金额  /////////
						    	Integer tos=(int) (totalPrice*100);
						    	 String jrc=null; String jrc1=null;
						    	Map<String,Object> resut=getPinPaymentResult(tos,ooi,user,customer_ip,ub);//支付
						    	  if(resut.get("code")!=null&&(int)resut.get("code")==201){//支付成功
						    		  ResponseCharges rc=(ResponseCharges) resut.get("obj");
						    		   jrc = JSONObject.fromObject(rc).toString();
						 ///////////////支付给fab平台的费用/////////////////
//							    		Double fab= PinPayHttpUtils.formula(totalPrice)-driverIncomecancelationFee;//总的费用-司机的收入  最终剩下的就是平台应该得到了
							    		if(fabcanComm>0){//给平台绑定的账号的费用是不收费的
							    			Map<String, String> fabMap=new HashMap<>();
							    			fabMap.put("amount", (fabcancelationFee*100)+"");//需要支付的金额
							    			fabMap.put("currency", "AUD");
							    			fabMap.put("description", u.getFirstName()+" Cancel the order platform for $"+fabcancelationFee);
							    			fabMap.put("recipient", cm.getFab_token());//收件人凭证
									    	Map<String,Object> fabresult=  PinPayHttpUtils.sendPinPayCreateTransfersPost(fabMap);
									    	 if(fabresult.get("code")!=null&&(int)fabresult.get("code")==201){//支付成功
									    		 ResponseTransfers rc1=(ResponseTransfers) fabresult.get("obj");
									    		   jrc1 = JSONObject.fromObject(rc1).toString();
									   		}else if(fabresult.get("code")!=null&&(int)fabresult.get("code")==422){
									   			ErrorResponseCard rc1=(ErrorResponseCard) fabresult.get("obj");
									   			String error="";
									   			if(rc!=null){
									   				List<ErrorMessage> liMessage=JSONArray.toList(JSONArray.fromObject(rc1.getMessages()), ErrorMessage.class);
									                for(ErrorMessage ee:liMessage){
									              	  error+=ee.getMessage()+" ; "; 
									                }
									   			}
									   			code=900;
									   			jrc1 =  JSONObject.fromObject(rc1).toString();;msg=error;
									   		}else if(fabresult.get("code")!=null&&(int)fabresult.get("code")==400){
									   			ErrorResponse400 rc1=(ErrorResponse400) fabresult.get("obj");
									   			jrc1 = JSONObject.fromObject(rc1).toString();
									   			code=900;msg=rc1.getError_description();
											}
									    	 PinpayRecord fabppr = new PinpayRecord(ooi.getId(),jrc1,(int)fabresult.get("code"),new Date(),3);//支付记录
								    		 pinpayRecordMapper.insertSelective(fabppr);
							    		} 
							    		 status=12;
						   		}else if(resut.get("code")!=null&&(int)resut.get("code")==422){
						   			ErrorResponseCard rc=(ErrorResponseCard) resut.get("obj");
						   			jrc =  JSONObject.fromObject(rc).toString();
						   			ReturnData rd=ChooseDeductions(ooi, u, ooi.getuId(), ooi.getUbId(), amount, customer_ip);//扣取没有拿到的钱
							   		code=rd.getCode();
						   			if(code!=200){
							   			status = 11;
							   		}
						   			msg=rd.getMsg();
						   		}else if(resut.get("code")!=null&&(int)resut.get("code")==400){
						   			ErrorResponse400 rc=(ErrorResponse400) resut.get("obj");
						   			jrc = JSONObject.fromObject(rc).toString();
						   			ReturnData rd=ChooseDeductions(ooi, u, ooi.getuId(), ooi.getUbId(), amount, customer_ip);//扣取没有拿到的钱
							   		code=rd.getCode();
						   			if(code!=200){
							   			status = 11;
							   		}
//						   			code=900;msg=rc.getError_description();
						   			msg=rd.getMsg();code=rd.getCode();
								}
						    	  PinpayRecord ppr = new PinpayRecord(ooi.getId(),jrc,(int)resut.get("code"),new Date(),1);//支付记录
					    		  pinpayRecordMapper.insertSelective(ppr);
					    		  OrderChargeDetail ocd = new OrderChargeDetail();
									ocd.setBookingFee(bookingFee);
									ocd.setTotalFee(totalPrice);
									ocd.setDriverId(ooi.getDirberId());
									ocd.setCalType(ooi.getCarType());
									ocd.setCreateTime(new Date());
									ocd.setOrderDriverSettlement(driverIncomecancelationFee);
									ocd.setOrderFabCommissions(0.0);
									if(fabcanComm>0){
										ocd.setOrderFabCommissions(fabcanComm);
									}
									ocd.setMinimumFare(minimumFare);
									ocd.setTotalMoney(totalPrice);
									ocd.setTotals(totalPrice);
									ocd.setOrderId(ooi.getId()+"");
									ocd.setuId(ooi.getuId());
									ocd.setCancelFee(cancle);
									orderChargeDetailMapper.insertSelective(ocd);//保存记录
							   ooi.setStatus(status);// 11 取消成功 待付款（余额不足等其他原因导致） 10已取消(不收费)
							   if(status==12){
								   ooi.setPayStatus(1);// 支付状态 0未支付 1已支付
							   }
			        		  u.setConsumetotal(u.getConsumetotal()+driverIncomecancelationFee);//周需要给司机的金额
			        		  userMapper.updateByPrimaryKeySelective(u);
							}else{//费用小于0 算不收费
								ooi.setStatus(10);// 10已取消(不收费)
			        			ooi.setPayStatus(1);// 支付状态 0未支付 1已支付
			        			status=10;
			        			bd = new BigDecimal(totalPrice);
							}
					   }
	            	}else{//未到达乘客上车地点 不收取服务费
	            		ooi.setStatus(10);// 10已取消(不收费)
	        			ooi.setPayStatus(1);// 支付状态 0未支付 1已支付
	        			status=10;
	        			bd = new BigDecimal(0.0);
	            	}
	            	ooi.setDriverName(u.getFirstName());
	            	ooi.setDriverPhone(u.getTelephone());
	    			ooi.setTotalPrice(bd);// 司机取消订单不收乘客的费用
	    			int n = orderItemsMapper.updateByPrimaryKeySelective(ooi);
	    			if (n == 0) {
	    				code = 202;
	    				msg = LanguageUtils.returnLan(language, "cancel_fail_gxdd");
	    			} else {
	    					DriverAccessory da = new DriverAccessory();
	    					da.setId(ooi.getCarId());
	    					da.setServerStatus(0);// 服务状态 0空闲 1服务中
	    					int nn = driverAccessoryMapper.updateByPrimaryKeySelective(da);
	    					if (code != 200&&code!=900) {
	    						TransactionAspectSupport.currentTransactionStatus().isRollbackOnly();
	    					}
	    			}
	    			UserMessage um = new UserMessage();
					um.setCreateTime(new Date());
					um.setmContext(reason);
					um.setmSummary("Your pickup request is canceled.");
					um.setName("Your pickup request is canceled.");
					um.setType(1);
					um.setuId(ooi.getuId());
					userMessageMapper.insertSelective(um);
	    			FireBaseUtil.sendMessageAlert(user.getUseEquipment(), "Your pickup request is canceled.");
	    			FireBaseUtil.postDataForFireBaseDataBase(user.getId()+"", "{\"orderId\":" + orderId + ",\"type\":1,\"status\":"+status+"}");
					// 向用户推送通知 司机取消的理由
				}
			return new ReturnData(code, msg);
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}finally {
			if(jedis!=null){
				jedis.close();
			}
		}
	}

	private Double getMileage(String lastLatitudeAndLongitude){
		Double mileage=0.0;
		if(!StringTools.isEmpty(lastLatitudeAndLongitude)){//如果记录的里程点不是空的
			System.out.println("lastLatitudeAndLongitude="+lastLatitudeAndLongitude);
			 List<String> StringLists = JSONArray.toList(JSONArray.fromObject(lastLatitudeAndLongitude), String.class);
			 int pointSize= StringLists.size();//总共的点的大小
			 float piecewise=(float)pointSize/(float)20;//经纬度能分成多少段
			 float piecewises=(float) (piecewise-(int)piecewise);//如果相减大于
			 int total=0;
			if(piecewises>0){
				total=(int)piecewise+1;
			}else{
				total=(int)piecewise;
			}
			List<String> pointList = new ArrayList<>();
			Map<String,Object> pointMap=new HashMap<>();
			StringBuffer sb=null;
			int count=0;
			for(int i=0;i<StringLists.size();i++){
				if(i%25==0){//25的倍数
					if(count!=0){
						System.out.println(sb);
						pointMap.put("count"+count, sb.toString());
						System.out.println("strs"+count+"="+sb);
					}
					count++;
					sb=new StringBuffer();
					sb.append(StringLists.get(i)+"|");
				}else{
					sb.append(StringLists.get(i)+"|");
				}
				if(i==StringLists.size()-1){
					pointMap.put("count"+count, sb.toString());
					System.out.println("strs"+count+"="+sb);
				}
			}	
     for(int i=1;i<=count;i++){//获取里程
   	  Double  mileage1=0.0;
   	  if(i>1){
   		  if(i==count){
      		   String org= (String)pointMap.get("count"+(i-1));
    			  String[] org1= org.replace("|", ";").split(";");
    			  String or=org1[org1.length-1];
    			  String de=(String)pointMap.get("count"+(i));
   			  String de1=de.replace("|", ";").split(";")[0];
   			  System.out.println("or==="+or);
      		   mileage1=getGoogleMileage(or,de1);//获取google的目前经纬度的里程
      	   }else{
      		   System.out.println("iiiiiiiiiiiiiii======"+i);
      		 String org= (String)pointMap.get("count"+(i));
      		 System.out.println("orgiiiiiiiiii======"+org);
			  String org1= org.replace("|", ";").split(";")[0];
			  String de=(String)pointMap.get("count"+(i+1));
			  if(StringTools.isEmpty(de)){
				  de=(String)pointMap.get("count"+(i));
			  }
			  String de1=de.replace("|", ";").split(";")[0];
			  mileage1=getGoogleMileage(org1, de1);//获取google的目前经纬度的里程
      	   }
   	  }else{
   		  String org= (String)pointMap.get("count"+(i));
			 String org1= org.replace("|", ";").split(";")[0];
			 String[] org2= org.replace("|", ";").split(";");
			 String o=org2[org2.length-1];
			   mileage1=getGoogleMileage(org1, o);//获取google的目前经纬度的里程
   	  }
   	   if(mileage1>0){
  	    	mileage+=mileage1;
  	       }
   	   System.out.println("mileage="+mileage1);
			}
		} 
		return mileage;
	}
	//收费线
	private Double getCarCaculationPointCharges_line(String carCaculationPointCharges_line){
		Double roadPrice=0.0;
		if(!StringTools.isEmpty(carCaculationPointCharges_line)){
			Map<String,Object> map1 = new HashMap<>();
			map1.put("type", 2);
			List<CarCaculationPointCharges> carCaculationPointList  = carCaculationPointChargesMapper.getList(map1);
			List<Map<String,List<String>>> listMap =  JSONArray.fromObject(carCaculationPointCharges_line);//将收费线的数据转为数组
			List< Map<String,Object>> lineList =new ArrayList();
			for(CarCaculationPointCharges ccr:carCaculationPointList){
				for(Map<String,List<String>> mapList :listMap){//遍历线mao
					List<String> lisString=mapList.get(ccr.getRoadName());//线经过的地方
					if(lisString!=null&&lisString.size()>0){
						String toll_station_form=lisString.get(0);
						String toll_station_to = lisString.get(lisString.size()-1);
						if(toll_station_form.equals(ccr.getPosition())&&toll_station_to.equals(ccr.getEndPosition())){//起点与终点
							roadPrice+=ccr.getCost();
						}
					}
				}
			}
		}
		return roadPrice;
	}
	//获取线
	private Double getCarCaculationPointCharges_point(String carCaculationPointCharges_point){
		Double roadPrice=0.0;Date nowDate = new Date();
		if(!StringTools.isEmpty(carCaculationPointCharges_point)){//该订单走过收费点
			Map<String,Object> map1 = new HashMap<>();
			map1.put("type", 1);
			List<CarCaculationPointCharges> carCaculationPointList  = carCaculationPointChargesMapper.getList(map1);
			JSONArray carc = JSONArray.fromObject(carCaculationPointCharges_point);//将收费点的数据转为数组
			List<String> toll_station_list = JSONArray.toList(carc);//途径的收费站列表
			List<String> stringList=new ArrayList<>();
			 for(CarCaculationPointCharges carCaculationPoint:carCaculationPointList){
				 for(String toll_station:toll_station_list){
					 if(toll_station.equals(carCaculationPoint.getPosition())){//途径了该收费点
						 if(nowDate.getDay()==5||nowDate.getDay()==6){//周末的收费标准收取费用
							 roadPrice+=carCaculationPoint.getWeekendCost();
						 }else{
							 roadPrice+=carCaculationPoint.getCost();
						 }
						 stringList.add(carCaculationPoint.getPosition());
					 }
				 }
			 }
		}
		return roadPrice;
	}
	
	/**
	 * 司机端 核实订单-改-P013 订单
	 * 
	 * @param mileage
	 * @param times
	 * @param orderId
	 * @return
	 */
	@Override
	public ReturnData getTheOrderPrice(String json) {
		Map<String, Object> map = new HashMap<>();
		OrderItems oii = StringTools.json2Obj(json, OrderItems.class);
		if (oii == null) {
			return new ReturnData(204, "");
		}
		Double mileage =0.0;
		Long orderId = oii.getOrderId();
		
		Jedis jedis=null;
		if(jedis==null){
			jedis=jedisPool.getResource();
		}
		Integer the_normal_time = 0;// 标准时长
		Double congestion_pricing = 0.0;
		Double roadPrice = 0.0;// 路桥费
		Double how_fee=0.0;
		Double mileage_fee =0.0;
		Double startPrice =0.0;
		Double minimumFare=0.0;
		double totalPrice =0.0;
		double bookingFee=0.0;
		double couponMoney= 0;// 优惠劵抵扣金额
		 Double totalPrice1 =0.0;//最终支付的金额【抵扣了优惠劵之后的费用】
		 Double concierge_price=0.0;//concierge 比fab ONE多出来的价格
		 double price_time_config=0.0;//堵车费多少收费用的比例
		// 里程
		Map<String, Object> m = new HashMap<>();
		try {
			OrderItems ooi = orderItemsMapper.selectByPrimaryKey(orderId);// 通过订单id查询订单
			map.put("carType", ooi.getCarType());// 查询该订单用车的收费标准【规则】
			// 服务结束时间
			// 服务开始时间 获取该订单的时长
			long diff =new Date().getTime()-ooi.getServiceStartTime().getTime();
			if(ooi.getServiceEndTime()!=null){
				 diff = ooi.getServiceEndTime().getTime() -ooi.getServiceStartTime().getTime();
			}
			long time = diff / (60 * 1000);// 改订单所用时长 分钟
			m.put("orderId", orderId);
			if (ooi.getStatus() == 11) {
				m.put("cancellationCharge", ooi.getTotalPrice());
			} else {
				CarCaculation carCaculation=null;
					String carcresult=jedis.get("carCaculation_carTypeObj"+ooi.getCarType());
					if(StringTools.isEmpty(carcresult)){
						carCaculation = carCaculationMapper.getCarCaculationDetail(map);// 计价规则
						JSONObject ja = JSONObject.fromObject(carCaculation);
						String jlist=ja.toString();
						jedis.set("carCaculation_carTypeObj"+ooi.getCarType(), jlist);
					}else{
						carCaculation = (CarCaculation) JSONObject.toBean(JSONObject.fromObject(carcresult),CarCaculation.class);
					}
					String lastLatitudeAndLongitude =jedis.hget("lastLatitudeAndLongitude",orderId+"");//获取里程点
					mileage=getMileage(lastLatitudeAndLongitude);//获取里程
					System.out.println("total_mileage="+mileage);
				if (carCaculation!=null) {
					// 针对每一个规则
					net.sf.json.JSONArray jo1 = net.sf.json.JSONArray.fromObject(oii.getPointCharges());
					ooi.setPointCharge(jo1.toString());
					ooi.setMileage(mileage);
					int num = orderItemsMapper.updateByPrimaryKeySelective(ooi);// 更新订单
																				// 里程与收费点
					//收费点
					String carCaculationPointCharges_point = jedis.hget("carCaculationPointCharges", "carCaculationPointCharges_point_"+oii.getOrderId()+"");//该订单收费点的数据
					roadPrice+=getCarCaculationPointCharges_point(carCaculationPointCharges_point);//收费点
					//收费点 线
					String carCaculationPointCharges_line = jedis.hget("carCaculationPointCharges", "carCaculationPointCharges_line_"+oii.getOrderId()+"");//该订单收费线的数据
					roadPrice+=getCarCaculationPointCharges_line(carCaculationPointCharges_line);
					map.put("uId", ooi.getuId());
					map.put("isUse", 1);// 1未使用
					List<UserCoupon> myCoupon = userCouponMapper.getCoupon(map);// 查询用户的优惠劵
					String configManager=jedis.get("configManager");
					ConfigManager cm=null;
					if(StringTools.isEmpty(configManager)){
						 cm = configManagerMapper.selectByPrimaryKey(1);
							JSONObject jo = JSONObject.fromObject(cm);
							jedis.set("configManager", jo.toString());
							price_time_config=cm.getPrice_time_config();
					}else{
						JSONObject jo = JSONObject.fromObject(configManager);
						cm = (ConfigManager) JSONObject.toBean(jo, ConfigManager.class);
						price_time_config=cm.getPrice_time_config();
					}
					the_normal_time=ooi.getTimes();//标准时长  下订单时存起来的
					Integer traffic_time = (int) (time-(the_normal_time+(the_normal_time*price_time_config)) );//堵车费
					if (traffic_time > 0) {
						congestion_pricing = traffic_time * carCaculation.getTrafficJamPrice();// 堵车费  
					}
					System.out.println("堵车时长="+traffic_time);
					// 金额越大越先用
					if (myCoupon.size() > 0) {
						couponMoney= myCoupon.get(0).getCouponOffsetMoney().doubleValue();
					}
					if(ooi.getCarType()==4){
						concierge_price=carCaculation.getExtraMoney();//concierge 二期规则为比fab ONE 多收19澳元且所有取消或者司机等乘客的时间长10分钟  该字段只有 concierge  使用
					}
					how_fee = time * carCaculation.getTimePrice();// 时长费  
					mileage = mileage / 1000;// 一公里多少钱
					 mileage_fee = mileage * carCaculation.getMileagePrice();// 里程费
					 startPrice = carCaculation.getStartPrice();// 起步价
					 minimumFare=carCaculation.getMinimumFare();// 最低消费
					 Double comp=startPrice + mileage_fee + how_fee+congestion_pricing;//需要与最新小费作比较的费用
					 bookingFee=carCaculation.getBookingFee();
					 Double tol= comp-minimumFare<0?minimumFare:comp;
					 totalPrice = tol + bookingFee+roadPrice+concierge_price;// 用户需支付的 总费用
					totalPrice1 = totalPrice - couponMoney;// 抵扣优惠劵之后的金额 订单金额-优惠劵的金额
					totalPrice1 = totalPrice1 > 0 ? totalPrice1 : 0;// 若抵扣之后
				}
			}
			m=encapsulationOffer(m,congestion_pricing,mileage,how_fee,mileage_fee,startPrice,minimumFare,time,roadPrice,bookingFee,couponMoney,totalPrice1,concierge_price);
			JSONObject joo=JSONObject.fromObject(m);
			jedis.hset("trip", ooi.getId()+"", joo.toString());
			return new ReturnData(m, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}finally {
			if(jedis!=null){
				jedis.close();
			}
		}
	}
	
	//返回报价Map
	public  Map<String,Object> encapsulationOffer(Map<String, Object> m,Double congestion_pricing,Double mileage,Double how_fee,Double mileage_fee,Double startPrice,Double minimumFare,long  time,Double roadPrice,Double bookingFee,Double couponMoney,Double totalPrice1,Double concierge_price){
		DecimalFormat df = new DecimalFormat("######0.00"); 
		m.put("congestion_pricing", df.format(congestion_pricing));// 堵车费
		m.put("mileage", mileage);// 里程
		m.put("how_fee", df.format(how_fee));// 时长费
		m.put("mileage_fee", df.format(mileage_fee));// 里程费
		m.put("startPrice", df.format(startPrice));// 起步价
		m.put("minimumFare", df.format(minimumFare));// 最低消费
		m.put("time", df.format(time));
		m.put("roadPrice", df.format(roadPrice));// 路桥费
		m.put("bookingFee", df.format(bookingFee));// 预定费
		m.put("couponMoney", couponMoney);
		String endTotalPrice = df.format(totalPrice1);
		m.put("totalPrice", endTotalPrice);
		m.put("concierge_price", df.format(concierge_price));
		return m;
	}

	// 获取标准时长
	private String getStandardTime(String latitudeAndLongitude, String destination) {
		Map<String, Object> params = new HashMap<>();
		/**
		 * origin 作为您路线计算起点的地址、纬度/经度文本值或地点 ID
		 * 如果您传递地址，路线服务将对字符串进行地理编码，并将其转换为纬度/经度坐标以计算路线。该坐标可能不同于 Google Maps
		 * Geocoding API 返回的值，例如可能是建筑入口而不是其中心。 origin=24+Sussex+Drive+Ottawa+ON
		 * 如果您传递坐标，它们将不加更改地直接用于计算路线。确保纬度值与经度值之间不存在空格。 origin=41.43206,-81.38992
		 * 地点 ID 必须带有 place_id: 前缀。只有当请求包括 API 密钥或 Google Maps APIs Premium Plan
		 * 客户端 ID 时，才能指定地点 ID。可以从 Google Maps Geocoding API 和 Google Places
		 * API（包括地点自动填充）检索地点 ID。如需查看使用来自“地点自动完成”的地点 ID
		 * 的示例，请参阅地点自动完成和路线。如需了解更多有关地点 ID 的内容，请参阅地点 ID 概览
		 * origin=place_id:ChIJ3S-JXmauEmsRUcIaWtf4MzE
		 */
		String[] origin=latitudeAndLongitude.split(",");
		String origin1=origin[1]+","+origin[0];
		params.put("origin", origin1);
		/**
		 * destination – 作为您路线计算终点的地址、纬度/经度文本值或地点 ID。destination 参数的选项与上述 origin
		 * 参数相同
		 */
		params.put("destination", destination);
		// params.put("departure_time", "1541202457");
		/**
		 * traffic_model（默认为 best_guess）– 指定在计算交通时间时使用的假设。此设置影响响应中
		 * duration_in_traffic 字段中返回的值，该字段包含根据历史平均值预测的交通时间。只能为请求中包括
		 * departure_time 的驾车路线指定 traffic_model 参数，并且只能在请求包括 API 密钥或 Google Maps
		 * APIs Premium Plan客户端 ID 时进行指定。该参数的可用值如下：
		 * 
		 * best_guess（默认值）表示返回的 duration_in_traffic
		 * 应为在同时考虑已知历史交通状况和实时交通状况的情况下对出行时间做出的最佳估计。departure_time
		 * 与当前时间越接近，实时交通状况就越重要。 pessimistic 表示返回的 duration_in_traffic
		 * 应在大多数日期长于实际出行时间，但在交通状况特别糟糕的日期，可能偶尔会发生超过该值的情况。 optimistic 表示返回的
		 * duration_in_traffic 应在大多数日期短于实际出行时间，但在交通状况特别理想的日期，可能偶尔会发生小于该值的情况。
		 * best_guess 的默认值将为大多数用例提供最有用的预测。best_guess 行程时间预测可能比 optimistic
		 * 的时间短或者比 pessimistic 的时间长，因为 best_guess 预测模式会整合实时交通信息。
		 */
		params.put("traffic_model", "best_guess");
		params.put("departure_time", new Date().getTime());
		/**
		 * key – 您的应用的 API 密钥。此密钥可以标识您的应用，以便进行配额管理。了解如何获取密钥。 注：Google Maps APIs
		 * Premium Plan 客户可以在 Directions 请求中使用 API 密钥或有效的客户端 ID 和数字签名。获取有关
		 * Premium Plan 客户身份验证参数的更多信息。
		 */
//		params.put("key", "AIzaSyBF5UoTfpN877xWxSreNi7ROOw6rbNDiRo");
//		params.put("key", "AIzaSyDl3z4QcAPaOPJ3ZWwPsXdbIJz9u1kGHGY");
		params.put("key", Constant.GOOGLE_API_KEY);
		String result = "";
		try {
			result = HttpRequestUtil.sendRequestByGet("https://maps.googleapis.com/maps/api/directions/json", params);
			System.out.println(result);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}

	private void saveFile(String result,HttpServletRequest request,OrderItems oi) {
		//经纬度
		StringBuffer latitudeAndLongitude = new StringBuffer();
		JSONArray jarr=JSONArray.fromObject(result);
		List<String> StringList = JSONArray.toList(jarr, String.class);
		for(String latlon: StringList){//拼接需要传递的纬经度
			String[] latlonlist=latlon.split(",");
			String latloncontent = latlonlist[1]+","+latlonlist[0];
			latitudeAndLongitude.append(latloncontent+"|");
		}
		 String realPath =  request.getSession().getServletContext().getRealPath("/");
         String path2 = realPath.substring(0,realPath.lastIndexOf(System.getProperty("file.separator")));
         String p = realPath.substring(0, (path2.lastIndexOf(System.getProperty("file.separator"))))+System.getProperty("file.separator")+"file"+System.getProperty("file.separator")+"FABposition";
		 File file = new File(p); 
		//把字符串转换成list
		if (!file.exists()) {
			file.mkdir();
            System.err.println(file + "已创建！");
        }
		 File file1 = new File(p, oi.getId()+".txt"); 
		 if (!file1.exists()) {
				try {
					file1.createNewFile();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	            System.err.println(file + "已创建！");
	        }
		 byte bt[] = new byte[1024];  
	        bt = result.getBytes();  
	        try {  
	            FileOutputStream in = new FileOutputStream(file1);  
	            try {  
	            	   in.write(bt, 0, bt.length);  
		                in.close(); 
	            } catch (IOException e) {  
	                // TODO Auto-generated catch block  
	                e.printStackTrace();  
	            }  
	        } catch (FileNotFoundException e) {  
	            // TODO Auto-generated catch block  
	            e.printStackTrace();  
	        }  
	}
	/**
	 * 司机确认账单
	 */
	@Override
	public ReturnData confirmTheBill(String json,HttpServletRequest request) {
		OrderChargeDetail ocd = StringTools.json2Obj(json, OrderChargeDetail.class);
		if (ocd == null) {
			return new ReturnData(201, LanguageUtils.returnLan(2, "list_empty"));
		}
		Map<String, Object> map = new HashMap<>();
		map.put("orderId", ocd.getOrderId());
		int code = 200; Date nowDate = new Date();Double mileage =0.0;
		String msg = LanguageUtils.returnLan(ocd.getLanguage(), "qrcg");
		Jedis jedis = null;
		if(jedis==null){
			jedis =jedisPool.getResource();
		}
		Double timeFee = ocd.getTimeFee() == null ? 0.0 : ocd.getTimeFee();// 时长费
		Double startFee = ocd.getStartFee() == null ? 0.0 : ocd.getStartFee();// 起步价
		Double serveiceCharge = 0.0;// 过路费
		Double bookingFee = ocd.getBookingFee() == null ? 0.0 : ocd.getBookingFee();//预定费 
		Double minimumFare=ocd.getMinimumFare()==null?0.0:ocd.getMinimumFare();//最低消费
		Double trafficJamPrice = ocd.getTrafficJamPrice()==null?0.0:ocd.getTrafficJamPrice();//堵车费
		Double concierge=0.0;//concierge 需要比fab ONE多收取的费用
		DriverAccessory da=new DriverAccessory();//修改司机的车的状态
		Double mileageMoney=0.0;//里程费
		CarCaculation carCaculation =null;
		try {
			List<OrderChargeDetail> list = orderChargeDetailMapper.getOrderChargeDetail(map);// 查询该订单是否已经确认过订单了
			if (list.size() > 0) {
				return new ReturnData(204, "Order confirmed. Can not repeat confirmation");
			}
			OrderItems oi = orderItemsMapper.selectByPrimaryKey(Long.parseLong(ocd.getOrderId()));// 更新行程的订单总价
			ocd.setuId(oi.getuId());
			if(!StringTools.isEmpty(ocd.getCleanness_remark())){//清洁费 描述内容 不能为空
				ocd.setCleaning_fee_audit(1);// 清洁费是否审核通过 1待审核 2审核通过 3审核不通过
				insertSug(oi, ocd);//保存记录
			}
			String result = jedis.hget("order", oi.getId()+"");
			String result1 = jedis.hget("lastLatitudeAndLongitude", oi.getId()+"");
			//经纬度
			StringBuffer latitudeAndLongitude = new StringBuffer();
				if (!StringUtils.isEmpty(result)) {
					saveFile(result, request, oi);//保存文件
				}
			User u = userMapper.selectByPrimaryKey(oi.getuId());//查询用户  记录 统计用户的消费金额 与里程
			da.setId(oi.getCarId());
			String trip=jedis.hget("trip", oi.getId()+"");
			if(!StringTools.isEmpty(trip)){
//				JSONObject jo = JSONObject.toBean(JSONObject.fromObject(trip))
				Map<String,Object> map1=StringTools.jsonToMap(trip);
				trafficJamPrice=Double.parseDouble((String)map1.get("congestion_pricing"));//堵车费
				System.out.println("确认账单时，拿到的交通费"+trafficJamPrice);
				Double mileage1 =Double.parseDouble((String) map1.get("mileage"));
				mileage =mileage1==0?mileage:mileage1;
				System.out.println("确认账单时，拿到的里程"+mileage);
				minimumFare =Double.parseDouble((String)map1.get("minimumFare"));
			}
			//收费点
			String carCaculationPointCharges_point = jedis.hget("carCaculationPointCharges", "carCaculationPointCharges_point_"+ocd.getOrderId()+"");//该订单收费点的数据
			List<Map<String,Object>> mmlist=new ArrayList<>();
			if(!StringTools.isEmpty(carCaculationPointCharges_point)){//该订单走过收费点
				jedis.hget("carCaculationPointCharges","carCaculationPointChargesPoint");
				Map<String,Object> map1 = new HashMap<>();
				map1.put("type", 1);
				List<CarCaculationPointCharges> carCaculationPointList  = carCaculationPointChargesMapper.getList(map1);
				JSONArray carc = JSONArray.fromObject(carCaculationPointCharges_point);//将收费点的数据转为数组
				List<String> toll_station_list = JSONArray.toList(carc);//途径的收费站列表
				List<String> stringList=new ArrayList<>();
				 for(CarCaculationPointCharges carCaculationPoint:carCaculationPointList){
					 for(String toll_station:toll_station_list){
						 if(toll_station.equals(carCaculationPoint.getPosition())){//途径了该收费点
							 if(nowDate.getDay()==5||nowDate.getDay()==6){//周末的收费标准收取费用
								 serveiceCharge+=carCaculationPoint.getWeekendCost();
							 }else{
								 serveiceCharge+=carCaculationPoint.getCost();
							 }
							 stringList.add(carCaculationPoint.getPosition());
						 }
					 }
				 }
				 Map<String,Object> pointList =new HashMap<>();
				 pointList.put("point_charge", stringList);
				 mmlist.add(pointList);
			}
			//收费点 线
			String carCaculationPointCharges_line = jedis.hget("carCaculationPointCharges", "carCaculationPointCharges_line_"+ocd.getOrderId()+"");//该订单收费线的数据
			if(!StringTools.isEmpty(carCaculationPointCharges_line)){
				Map<String,Object> map1 = new HashMap<>();
				map1.put("type", 2);
				List<CarCaculationPointCharges> carCaculationPointList  = carCaculationPointChargesMapper.getList(map1);
				List<Map<String,List<String>>> listMap =  JSONArray.fromObject(carCaculationPointCharges_line);//将收费线的数据转为数组
				List< Map<String,Object>> lineList =new ArrayList();
				for(CarCaculationPointCharges ccr:carCaculationPointList){
					for(Map<String,List<String>> mapList :listMap){//遍历线mao
						List<String> lisString=mapList.get(ccr.getRoadName());//线经过的地方
						if(lisString!=null&&lisString.size()>0){
							Map<String,Object> stringList=new HashMap<>();
							Map<String,Object> ms = new HashMap<>();
							String toll_station_form=lisString.get(0);
							String toll_station_to = lisString.get(lisString.size()-1);
							if(toll_station_form.equals(ccr.getPosition())&&toll_station_to.equals(ccr.getEndPosition())){//起点与终点
								serveiceCharge+=ccr.getCost();
							}
							ms.put("toll_station_form", toll_station_form);
							ms.put("toll_station_to", toll_station_to);
							stringList.put(ccr.getRoadName(), ms);
							lineList.add(stringList);
						}
					}
				}
				Map<String,Object> pointList =new HashMap<>();
				 pointList.put("line_charge", lineList);
				 mmlist.add(pointList);
			}
//			jedis.hdel("carCaculationPointCharges", "carCaculationPointCharges_point_"+ocd.getOrderId()+"");
//			jedis.hdel("carCaculationPointCharges", "carCaculationPointCharges_line_"+ocd.getOrderId()+"");//删除数据
			String carcresult=jedis.get("carCaculation_carTypeObj"+oi.getCarType());
			if(StringTools.isEmpty(carcresult)){
				carCaculation = carCaculationMapper.getCarCaculationDetail(map);// 计价规则
				JSONObject ja = JSONObject.fromObject(carCaculation);
				String jlist=ja.toString();
				jedis.set("carCaculation_carType"+oi.getCarType(), jlist);
				
			}else{
				carCaculation = (CarCaculation) JSONObject.toBean(JSONObject.fromObject(carcresult),CarCaculation.class);
			}
			if(carCaculation!=null){
				 bookingFee=carCaculation.getBookingFee();
				 minimumFare = carCaculation.getMinimumFare();
				 mileageMoney=mileage*carCaculation.getMileagePrice();//里程费
					 if(oi.getCarType()==4&&carCaculation.getCarType()==4){//用车类型为concierge 则需要加上多出来的费用
							concierge=carCaculation.getExtraMoney();
						}
    		   }
			Double totalPrice =0.0;Double totalPrice2 =0.0;
	    	Double to=	mileageMoney+timeFee+startFee+trafficJamPrice;//司机与最低消费作比较的费用
	    	totalPrice2 = to < minimumFare ? minimumFare : to;//如果我的费用小于最小消费  则使用最低消费
	    	totalPrice+=totalPrice2+serveiceCharge+bookingFee;//用户需要支付的总的费用
	    	ocd.setTotalFee(totalPrice);
			Double fab=totalPrice2;//平台需要提成
			Double fabCommission=0.0;//p平台扣取支付手续费之后能拿到的实际金额
			map.put("uId", oi.getuId());
			map.put("isUse", 1);// 1未使用
			List<UserCoupon> myCoupon = userCouponMapper.getCoupon(map);// 查询用户的优惠劵
			String pointCharge = JSONArray.fromObject(mmlist).toString();//走过的收费点的记录
			double ct= 0;// 优惠劵抵扣金额 
			String jrc =null;String jrc1=null;UserCoupon uc =null;
			// 金额越大越先用
			if (myCoupon.size() > 0) {
				ct= myCoupon.get(0).getCouponOffsetMoney().doubleValue();
				 uc =myCoupon.get(0);
				uc.setIsUse(2);
				uc.setOrderNo(oi.getOrderNo());
				uc.setOrderId(oi.getId());
				uc.setSpendingTime(nowDate);//消费时间
				int n = userCouponMapper.updateByPrimaryKeySelective(uc);//更新该优惠劵为已使用
				oi.setCouponId(myCoupon.get(0).getId());//使用优惠劵的id
			}
			int notPayCount=orderItemsMapper.notPay(oi.getuId());//没有支付的次数
			if(notPayCount==0){
				totalPrice=	totalPrice-1;//扣掉一澳元  由于绑定银行卡时扣取了用户1澳元
			}
			   totalPrice+=concierge;//若是concierge则会多出来费用
			   ocd.setTotalMoney(totalPrice);//
				Double totalPrice1 = totalPrice - ct;// 抵扣优惠劵之后的金额 订单金额-优惠劵的金额
				totalPrice1 = totalPrice1 > 0 ? totalPrice1 : 0;// 若抵扣之后
																// >0则实际支付金额为需要支付的
																// 若抵扣之后《0
																// 则无需支付
					Integer amount=0;
       if(uc!=null&&!RegexUtil.isNull(uc.getEnterpriseId())){//是企业优惠劵
    	   UserBrank enterprise=userBrankMapper.getEnterpriseBrank(uc.getEnterpriseId());
		        	if(totalPrice1>0){//优惠劵直接抵扣了  最低支付1澳元 如果需要支付的金额小于1 那么就没有必要调用接口
				    	Map<String,Object> resut=getPinPaymentResult(amount,oi,u,ocd.getCustomer_ip(),enterprise);//支付
				    	  if(resut.get("code")!=null&&(int)resut.get("code")==201){//支付成功
				    		  ResponseCharges rc=(ResponseCharges) resut.get("obj");
				    		   jrc = JSONObject.fromObject(rc).toString();
				    		User enterpriseUser=   userMapper.selectByPrimaryKey(uc.getEnterpriseId());
				    		enterpriseUser.setAvailableMoney((int)(enterpriseUser.getAvailableMoney()-ct));
				    		userMapper.updateByPrimaryKeySelective(enterpriseUser);//更新企业可用的金额
				    	  }else if(resut.get("code")!=null&&(int)resut.get("code")==422){
					   			ErrorResponseCard rc=(ErrorResponseCard) resut.get("obj");
					   			String error="";
					   			if(rc!=null){
					   				List<ErrorMessage> liMessage=JSONArray.toList(JSONArray.fromObject(rc.getMessages()), ErrorMessage.class);
					                for(ErrorMessage ee:liMessage){
					              	  error+=ee.getMessage()+" ; "; 
					                }
					   			}
					   			code=900;
					   			jrc =  JSONObject.fromObject(rc).toString();;msg=error;
					   		}else if(resut.get("code")!=null&&(int)resut.get("code")==400){
					   			ErrorResponse400 rc=(ErrorResponse400) resut.get("obj");
					   			jrc = JSONObject.fromObject(rc).toString();
					   			code=900;msg=rc.getError_description();
							}
					    	  PinpayRecord ppr = new PinpayRecord(oi.getId(),jrc,(int)resut.get("code"),new Date(),4);//支付记录
				    		  pinpayRecordMapper.insertSelective(ppr);
		        	}
				}
				 if(carCaculation!=null){
	    			   fabCommission=(fab*carCaculation.getFabCommission())-PinPayHttpUtils.formula(totalPrice2);//fab平台该笔订单 能拿到的费用 
	    		   }
				if(totalPrice1>0){//调用支付 扣取用户需要支付的金额
					UserBrank ub = userBrankMapper.selectByPrimaryKey(oi.getUbId());//冻结预估价的卡
			      //////////用户支付 totalPrice1 金额  /////////
			    	Integer tos=(int) (totalPrice1*100);
			    	Map<String,Object> resut=getPinPaymentResult(tos,oi,u,ocd.getCustomer_ip(),ub);//支付
			    	  if(resut.get("code")!=null&&(int)resut.get("code")==201){//支付成功
			    		  ResponseCharges rc=(ResponseCharges) resut.get("obj");
			    		   jrc = JSONObject.fromObject(rc).toString();
			    		   oi.setFatzebraId(rc.getResponse().getToken());
			               ///////////////支付给fab平台的费用/////////////////
			 					    	if(fabCommission>0){
//			 					    		ConfigManager cm=configManagerMapper.selectByPrimaryKey(1);//查询配置信息
			 					    		ConfigManager cm=null;
			 				    			String configManager=jedis.get("configManager");
			 				    			if(StringTools.isEmpty(configManager)){
			 				    				 cm = configManagerMapper.selectByPrimaryKey(1);
			 				    					JSONObject jo = JSONObject.fromObject(cm);
			 				    					jedis.set("configManager", jo.toString());
			 				    			}else{
			 				    				JSONObject jo = JSONObject.fromObject(configManager);
			 				    				cm = (ConfigManager) JSONObject.toBean(jo, ConfigManager.class);
			 				    			}
			 					    		Map<String, String> fabMap=new HashMap<>();
			 					    		fabMap.put("amount", (int)(fabCommission*100)+"");//需要支付的金额
			 					    		fabMap.put("currency", "AUD");
			 					    		fabMap.put("description", u.getFirstName()+"  the order platform for $"+fabCommission);
			 					    		fabMap.put("recipient", cm.getFab_token());//收件人凭证
			 						    	Map<String,Object> fabresult=  PinPayHttpUtils.sendPinPayCreateTransfersPost(fabMap);
			 						    	 if(fabresult.get("code")!=null&&(int)fabresult.get("code")==201){//支付成功
			 						    		 ResponseTransfers rc1=(ResponseTransfers) fabresult.get("obj");
			 						    		   jrc1 = JSONObject.fromObject(rc1).toString();
			 						   		}else if(fabresult.get("code")!=null&&(int)fabresult.get("code")==422){
			 						   			ErrorResponseCard rc1=(ErrorResponseCard) fabresult.get("obj");
			 						   			String error="";
			 						   			if(rc!=null){
			 						   				List<ErrorMessage> liMessage=JSONArray.toList(JSONArray.fromObject(rc1.getMessages()), ErrorMessage.class);
			 						                for(ErrorMessage ee:liMessage){
			 						              	  error+=ee.getMessage()+" ; "; 
			 						                }
			 						   			}
//			 						   		ReturnData rd=ChooseDeductions(oi, u, oi.getuId(), oi.getUbId(), amount, ocd.getCustomer_ip());//扣取没有拿到的钱
//			 					   		   code=rd.getCode(); //			 						   			code=900;
			 						   			jrc1 =  JSONObject.fromObject(rc1).toString();;msg=error;
			 						   		}else if(fabresult.get("code")!=null&&(int)fabresult.get("code")==400){
			 						   			ErrorResponse400 rc1=(ErrorResponse400) fabresult.get("obj");
//			 						   		    ReturnData rd=ChooseDeductions(oi, u, oi.getuId(), oi.getUbId(), amount, ocd.getCustomer_ip());//扣取没有拿到的钱
//				 					   		    code=rd.getCode(); //			 						   			code=900;
				 						   		jrc1 =  JSONObject.fromObject(rc1).toString();;msg=rc1.getError_description();
			 								}
			 						    	 PinpayRecord fabppr = new PinpayRecord(oi.getId(),jrc1,(int)fabresult.get("code"),new Date(),3);//支付记录
			 					    		 pinpayRecordMapper.insertSelective(fabppr);  
			 					    	}	
			 		///////////////////支付给平台的费用///////////////////			    
			   		}else if(resut.get("code")!=null&&(int)resut.get("code")==422){
			   			ErrorResponseCard rc=(ErrorResponseCard) resut.get("obj");
			   			ReturnData rd=ChooseDeductions(oi, u, oi.getuId(), oi.getUbId(), amount, ocd.getCustomer_ip());//扣取没有拿到的钱
				   		code=rd.getCode(); //			 						   			code=900;
					   	jrc1 =  JSONObject.fromObject(rc).toString();;msg=rd.getMsg();
			   		}else if(resut.get("code")!=null&&(int)resut.get("code")==400){
			   			ErrorResponse400 rc=(ErrorResponse400) resut.get("obj");
			   			jrc = JSONObject.fromObject(rc).toString();
//			   			code=900;msg=rc.getError_description();
			   		    ReturnData rd=ChooseDeductions(oi, u, oi.getuId(), oi.getUbId(), amount, ocd.getCustomer_ip());//扣取没有拿到的钱
			   		    code=rd.getCode(); //	
			   		    code=900;
				   		jrc1 =  JSONObject.fromObject(rc).toString();;msg=rd.getMsg();
					}
			    	  PinpayRecord ppr = new PinpayRecord(oi.getId(),jrc,(int)resut.get("code"),new Date(),1);//支付记录
		    		  pinpayRecordMapper.insertSelective(ppr);
					//////////////////////
				}
				ocd.setTotals(totalPrice1);//更新使用优惠劵之后 客户  需要支付的金额
				BigDecimal bd = new BigDecimal(totalPrice1);
				oi.setMileage(ocd.getMileage());// 最终的里程
				oi.setTimes(ocd.getTime());// 总时长
				oi.setTotalPrice(bd);// 用户需要支付的金额
				oi.setPointCharge(pointCharge);
				
				if(code==200){
						oi.setStatus(8);// 订单为 已完成(未评价) 
						UserMessage um = new UserMessage();//更新消息
						um.setCreateTime(new Date());
						um.setmContext("Order number:"+oi.getOrderNo()+", Rider paid.");
						um.setmSummary("Rider paid");
						um.setType(2);
						um.setuId(oi.getDirberId());
						userMessageMapper.insertSelective(um);
					//用户第二次支付时，判断是否是他邀请的用户
					if(u.getUserOrderCount()!=null&&u.getUserOrderCount()==1){//首次下单  计算邀请人数
					String beiinvitecode=	u.getInviattionCode();//如果这个邀请码存在  则表示是被司机邀请的 因为用户没有邀请码
					Map<String,Object> inviteMap=new HashMap<>();
						if(!StringTools.isEmpty(beiinvitecode)){//注册时填写   司机邀请码  算 司机邀请 赠送给司机5元的红包 直接赠送
							inviteMap.put("inviattionCode", beiinvitecode);
							List<User> list1=userMapper.getLogin(inviteMap);
							if(list1.size()>0){
								User uus = list1.get(0);
								uus.setInvitenum(uus.getInvitenum()+1);
							int	inv=	userMapper.updateByPrimaryKeySelective(uus);//更新用户的邀请人数
								///////平台给司机划账  5元现金
							PlatformForTheDriver(oi.getDirberId());//给司机送5澳元
							
								//需要支付记录
								PlayTheRewardReward  ptrr = new PlayTheRewardReward();
								ptrr.setAmout(5.0);
								ptrr.setCreateTime(new Date());
								ptrr.setuId(uus.getId());
								ptrr.setType(2);
								int num1=playTheRewardRewardMapper.insertSelective(ptrr);//保存打赏、平台奖励，司机与平台结算使用
								if(num1==0){
									return new ReturnData(309,LanguageUtils.returnLan(1, "yqyhhdyhjsb"));
								}else{
									UserMessage um1 = new UserMessage();
									um1.setCreateTime(new Date());
									um1.setmContext("You invited a new User【"+u.getTelephone()+"】, Fab reward you with $5 AUD coupon.");
									um1.setmName("Invitation Rewards");
									um1.setmSummary("Invitation Rewards");
									um1.setuId(uus.getId());
									um1.setType(1);
									userMessageMapper.insertSelective(um1);//保存记录
								}
								FireBaseUtil.sendMessageAlert(uus.getUseEquipment(), "You invited a new User 【"+u.getTelephone()+"】, Fab reward you with $5 AUD coupon.");
								FireBaseUtil.postDataForFireBaseDataBase(uus.getId()+"", "{\"type\":6,\"orderId\":0,\"amount\":5}");
							}
						}else{ //查询是否是用户邀请  用户分享邀请时，会填写他要邀请的人的手机号码
							inviteMap.put("userBeinvitephone", u.getTelephone());
							List<User> list1=userMapper.getLogin(inviteMap);
							if(list1.size()>0){
								User uus = list1.get(0);
								uus.setInvitenum(uus.getInvitenum()+1);
								int inv=userMapper.updateByPrimaryKeySelective(uus);//更新用户的邀请人数
								if(inv==0){
									return new ReturnData(309,LanguageUtils.returnLan(1, "gxyqjlsb"));
								}else{
									BigDecimal bd1 = new BigDecimal(5);//固定送5澳元
									uc.setCouponMoney(bd1);
									uc.setCouponName("Invitation Rewards");
									uc.setCouponOffsetMoney(bd);
									uc.setCreateTime(new Date());
									uc.setCouponNo(gCoupoNo());
									uc.setCouponCode(RandomUtil.getRandomNumberNozeroStart(11));
									uc.setType(2);
									uc.setTelephone(uus.getTelephone());
									uc.setuId(uus.getId().toString());
									int ucnum=userCouponMapper.insertSelective(uc);//
									if(ucnum==0){
										return new ReturnData(309,LanguageUtils.returnLan(1, "yqyhhdyhjsb"));
									}else{
										UserMessage um2 = new UserMessage();
										um2.setCreateTime(new Date());
										um2.setmContext("User【"+u.getTelephone()+"】invited by you completed their first trip, Fab reward you with a coupon.");
										um2.setmName("Invitation Rewards");
										um2.setmSummary("Invitation Rewards");
										um2.setuId(uus.getId());
										um2.setType(1);
										userMessageMapper.insertSelective(um2);//保存记录
									}
								}
							}
						}
					}
					FireBaseUtil.postDataForFireBaseDataBase(u.getId()+"", "{\"type\":1,\"status\":8,\"orderId\":"+oi.getId()+"}");
				}else {//支付失败
					code=200;
					oi.setStatus(14);// 司机结束服务，乘客去支付，但是支付余额不足，没有完成支付,支付成功订单状态为已完成（待评价） 
					UserMessage um = new UserMessage();//更新用户信息消息 提示他未支付成功
					um.setCreateTime(new Date());
					um.setmContext("Your order number is:"+oi.getOrderNo()+" ,not paid. The reason is that:"+jrc);
					um.setmSummary("Rider paid");
					um.setType(1);
					um.setuId(oi.getuId());
					userMessageMapper.insertSelective(um);
					FireBaseUtil.sendMessageAlert(u.getUseEquipment(), "Thank you and have a fabulous day!");
					FireBaseUtil.postDataForFireBaseDataBase(u.getId()+"", "{\"type\":1,\"status\":14,\"orderId\":"+oi.getId()+"}");
				}
				// 去支付
				int oin = orderItemsMapper.updateByPrimaryKeySelective(oi);
				if (oin == 0) {
					code = 300;
					msg = LanguageUtils.returnLan(ocd.getLanguage(), "update_order_failed");
				}
				Map<String, Object> dmap = new HashMap<>();
				dmap.put("dirberId", oi.getDirberId());// 查询我的订单
				Integer[] orderStatus = {  2, 3, 4, 5,7 };// 未完成支付
				dmap.put("orderStatus", orderStatus);
				List<OrderItems> dlist = orderItemsMapper.getOrderItems(dmap);
				//如果该司机有服务中的订单  则不修改用车在用状态
				if(dlist.size()==0){ 
					da.setServerStatus(0);//司机的车辆状态为空闲
					int damn=driverAccessoryMapper.updateByPrimaryKeySelective(da);//更新司机的车
					if(damn == 0){
						return new ReturnData(302,LanguageUtils.returnLan(ocd.getLanguage(), "update_car_failed"));
					}
				}
				u.setConsumetotal(u.getConsumetotal()+totalPrice1);//我总共实际支付的金额
				u.setMileage(u.getMileage()+ocd.getMileage());//实际订单的里程
				u.setUserOrderCount(u.getUserOrderCount()+1);//用户支付成功之后 更新用户的下单次数
				int un=userMapper.updateByPrimaryKeySelective(u);//
				if(un == 0){//更新用户失败
					code = 301;
					msg = LanguageUtils.returnLan(ocd.getLanguage(), "update_user_failed");
				}
			ocd.setConcierge_price(concierge);
			ocd.setBookingFee(bookingFee);	//预定费
			ocd.setCalType(oi.getCarType());
			ocd.setCreateTime(new Date());
			ocd.setCouponMoney(ct);//优惠劵抵扣金额
			
			if(carCaculation!=null){//保存周结算时 司机能拿到的收成
				if(fabCommission>0){
					ocd.setOrderFabCommissions(fabCommission);
				}else{
					ocd.setOrderFabCommissions(0.0);
				}
				Double orderDriverSettlement=(totalPrice-(fab*carCaculation.getFabCommission()));//里程+时长+起步价+过路费+堵车费+小费（打赏的时候加进去）+清洁费（后台审核时加进去）
				ocd.setOrderDriverSettlement(orderDriverSettlement);//司机周结算时 可得费用
			}
			System.out.println("确认订单 --------------平台能拿到的提成"+fabCommission);
			ocd.setTrafficJamPrice(trafficJamPrice);
			ocd.setCreateTime(new Date());
			int num = orderChargeDetailMapper.insertSelective(ocd);
			if (num == 0) {
				code = 202;
				msg = LanguageUtils.returnLan(ocd.getLanguage(), "cost_detail_fail");
			}
			//订单处理完成之后 给用户发送 email 账单信息
			sendEmailForRider(oi,ocd,u.getEmail());
			
			 jedis.hdel("order", oi.getId()+"");//删除缓存中订单
			 jedis.hdel("lastLatitudeAndLongitude", oi.getId()+"");
			 
			return new ReturnData(code, msg);
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}finally {
			if(jedis!=null){
				jedis.close();
			}
		}
	}
	//平台送给司机的5澳元扣款
	private void PlatformForTheDriver(Long driverId){
		UserBrank ub=userBrankMapper.getEnterpriseBrank(driverId);
		 Map<String,String> sendBalanceMap=new HashMap<>();
			Map<String,Object> ResponseBalanceMap=	PinPayHttpUtils.getBalance(sendBalanceMap);	 
			 if(ResponseBalanceMap!=null&&(int)ResponseBalanceMap.get("code")==200){//查询成功
				 String rb= (String)ResponseBalanceMap.get("obj");
  				ResponseBalance rb1=StringTools.json2Obj(rb, ResponseBalance.class);
  				Integer amount=rb1.getResponse().getAvailable().get(0).getAmount();
  				if(amount!=null&&amount>500){//比较 如果可用余额大于转账给司机的金额 就转账  不够就不转
  					System.out.println("奖励司机5澳元 result=" + 5);
						Map<String, String> sendMap=new HashMap<>();
				    	sendMap.put("amount", 500+"");//需要支付的金额
				    	sendMap.put("currency", "AUD");
				    	sendMap.put("description", "Earnings for this week");
				    	sendMap.put("recipient", ub.getAvoidCloseToPayToken());//收件人凭证
				    	Map<String,Object> resut=	PinPayHttpUtils.sendPinPayCreateTransfersPost(sendMap);
  				}
  				}
			 }
	
	
	
	//给乘客发送该订单的账单信息 email
	private void sendEmailForRider(OrderItems oi,OrderChargeDetail ocd,String u_email){
		Double total=ocd.getTotals()==null?0.0:ocd.getTotals();
		String context = " <div style=\" background: #cde4e1;width:900px; \">" + "<ul style=\" list-style-type: none; \">  <li>"
				+ " <table style=\"width: 733px;\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"
				+ "<tbody><tr> <th style=\"text-align:  left;\">Date</th><th style=\"text-align:  left;\">Time</th><th style=\"text-align:  left;\">From</th><th style=\"text-align:  left;\">To</th>"
				+ "</tr>  <tr>" + " <td style=\"text-align:  left;\">"+DateUtil.format(oi.getCreateTime(), "yyyy-MM-dd")+"</td>"
				+ " <td style=\"text-align:  left;\">"+DateUtil.format(oi.getCreateTime(), "HH:mm")+"</td>"
				+ " <td style=\"text-align:  left;\"><span style='font-size:8px'>"+oi.getDepartureLocation()+"</span></td><td style=\"text-align:  left;\"><span style='font-size:8px'>"+oi.getArrivedLocation()+"</span></td> "
				+ "</tr>" + " </tbody></table></li>" + "<li style=\" margin-left: 20px; margin-top: 10px; \">"
				+ " <table style=\"width: 755px;\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">" + " <tbody><tr>"
				+ " <th style=\"text-align:  right;\">Time</th><th style=\"text-align:  right;\">Distance</th><th style=\"text-align: right;\">Toll</th><th style=\"text-align: right;\">Tip</th><th style=\"text-align: right;\">CT</th><th style=\"text-align: right;\">Booking</th><th style=\"text-align: right;\">Fare</th>"
				+ "<th style=\"text-align: right;\">fab</th><th style=\"text-align: right;\">Payout</th>"
				+ " </tr> <tr>"
				+ " <td style=\"text-align: right;\">"+(ocd.getTime()==null?0.0:ocd.getTime())+"mins</td> <td style=\"text-align: right;\">"+(ocd.getMileage()==null?0.0:ocd.getMileage())+"kms</td> </tr><tr>"
				+ " <td style=\"text-align: right;\">$"+(ocd.getTimeFee()==null?0.0:ocd.getTimeFee())+"</td> <td style=\"text-align: right;\">$"+(ocd.getMileageMoney()==null?0.0:ocd.getMileageMoney())+"</td> <td style=\"text-align: right;\">$"+(ocd.getServeiceCharge()==null?0:ocd.getServeiceCharge())+"</td><td style=\"text-align: right;\">$"+(ocd.getTip()==null?0:ocd.getTip())+"</td> "
				+ "<td style=\"text-align: right;\">$"+(ocd.getTrafficJamPrice()==null?0.0:ocd.getTrafficJamPrice())+"</td> <td style=\"text-align: right;\">$"+(ocd.getBookingFee()==null?0.0:ocd.getBookingFee())+"</td> <td style=\"text-align: right;\">$"+(ocd.getTimeFee()==null?0.0:ocd.getTimeFee())+"</td><td style=\"text-align: right;\">$"+(ocd.getOrderFabCommissions()==null?0.0:ocd.getOrderFabCommissions())+"</td><td style=\"text-align: right;\"><a style=\"text-decoration-line:  underline;\">$"+total+"</a></td>"
				+ " </tr>  </tbody></table> </li>"
				+ "<li> <div style=\"height:80px;position: relative;\"> <ul style=\" list-style-type:  none; \">"
				+" <li style=\"margin-left:650px;\"> <div><span>Total &nbsp;&nbsp;$"+total+"</span></div><div><span>GST&nbsp;&nbsp;$"+((double)total/11)+"</span></div>  </li> </ul> </div>  </li>"
				+ "   </ul> </div>";
		try {
			SendmailUtil.sendEmail("Fab Rideslous", context, u_email);
		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
public void	insertSug(OrderItems oi,OrderChargeDetail ocd){
		SugFeedback sug = new SugFeedback();//保存清洁费记录
		sug.setAccount(oi.getDriverPhone());
		sug.setDriverId(oi.getDirberId());
		sug.setImgs(ocd.getCleanness_img());
		sug.setMsgcontent(ocd.getCleanness_remark());
		sug.setMsgdate(new Date());
		sug.setMsgtitle(ocd.getCleanness_remark());
		sug.setOrderId(oi.getId());
		sug.setOrderNo(oi.getOrderNo());
		sugFeedbackMapper.insertSelective(sug);
	}
	private String gCoupoNo(){
		String no=userCouponMapper.getMaxNo();
		if(StringTools.isEmpty(no)){
			no="YQ00001";
		}else{
			Integer no1 =Integer.parseInt(no)+1;
			if(no1<10){
				no = "YQ0000"+no1;
			}else if(no1>=10&no1<100){
				no = "YQ000"+no1;
			}else if(no1>=100&no1<1000){
				no = "YQ00"+no1;
			}else if(no1>=1000&no1<10000){
				no = "YQ0"+no1;
			}else{
				no = "YQ"+no1;
			}
		}
		return no;
	}
	//选择扣款 该方法调用是在扣款失败之后调用
	private ReturnData ChooseDeductions(OrderItems oi,User u,Long uId,Long  ubId,Integer amount,String customer_ip){
		List<UserBrank> list=userBrankMapper.getUserCards(uId);//查询出来我有的银行卡列表信息
		int code=200;boolean flag=true;String msg="success";
		for(UserBrank ub:list){
			//由于引用类型超过基本类型的范围之后 应该比较的是内容 并不是位置 如果使用==会直接比较位置  所以获取Long的longValue 
			if(ub.getUbId().longValue()!=ubId.longValue()){//如果当前的这张卡没有被使用 那么需要用于扣款 
		    	Map<String,Object> resut=getPinPaymentResult(amount,oi,u,customer_ip,ub);//支付
		    	  if(resut.get("code")!=null&&(int)resut.get("code")==201){//支付成功
		    		  break;
		    	  }else if(resut.get("code")!=null&&(int)resut.get("code")!=201){
			   			code = (int)resut.get("code");flag=false;
			   			 if(resut.get("code")!=null&&(int)resut.get("code")==422){
					   			ErrorResponseCard rc=(ErrorResponseCard) resut.get("obj");
					   			String error="";
					   			if(rc!=null){
					   				List<ErrorMessage> liMessage=JSONArray.toList(JSONArray.fromObject(rc.getMessages()), ErrorMessage.class);
					                for(ErrorMessage ee:liMessage){
					              	  error+=ee.getMessage()+" ; "; 
					                }
					   			}
					   			msg=error;
					   		}else if(resut.get("code")!=null&&(int)resut.get("code")==400){
					   			ErrorResponse400 rc=(ErrorResponse400) resut.get("obj");
					   			msg=rc.getError_description();
							}
			   		}
			    	  PinpayRecord ppr = new PinpayRecord(oi.getId(),msg,(int)resut.get("code"),new Date(),4);//支付记录
		    		  pinpayRecordMapper.insertSelective(ppr);//将所有的调用接口的记录都保存起来
			}
		}
		
		return new ReturnData(flag, code, msg);
	}
	
	
	//通过起点与终点经纬度计算司机到达成功时间
	public Map<String,Object> getGoogleTimes(String origins,String destinations){
		Map<String,Object> m = new HashMap<>();
		String time="";long longTime=0;
		Map<String, Object> params = new HashMap<>();
			 params.put("units", "imperial");
			params.put("origins", origins);//起点纬经度
			params.put("destinations", destinations);//终点纬经度 多个点
			params.put("key", Constant.GOOGLE_API_KEY);
			String result = "";
			try {
				result = HttpRequestUtil.sendRequestByGet("https://maps.googleapis.com/maps/api/distancematrix/json", params);
				System.out.println("获取司机列表，获取时间google="+result);
				if(!StringTools.isEmpty(result)){//返回有数据
					JSONObject googleResult=JSONObject.fromObject(result);
					String status=(String) googleResult.get("status");
					if("OK".equals(status)){//如果是成功
//						GoogleMileage gm=(GoogleMileage) JSONObject.toBean(JSONObject.fromObject(), GoogleMileage.class) ;
						JSONArray rowsja = JSONArray.fromObject(googleResult.get("rows"));
						if(rowsja.size()>0){
							GoogleMileage gm=(GoogleMileage) JSONObject.toBean(JSONObject.fromObject(rowsja.get(0)), GoogleMileage.class) ;
							if(gm!=null){
								List<GoogleMileageElementsObj> elementslist=JSONArray.toList(JSONArray.fromObject(gm.getElements()),GoogleMileageElementsObj.class);
								System.out.println("GoogleMileageElements ===="+elementslist);
//								GoogleMileageElementsObj elements =elementslist.get(0);
//								System.out.println("elements="+elements);
								for(GoogleMileageElementsObj gmeo:elementslist){
									if("OK".equals(gmeo.getStatus())){
										time=gmeo.getDuration().getText();
										longTime=gmeo.getDuration().getValue();
										System.out.println("司机列表时，获取时长="+time);
									}
								}
							}
						}
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("司机获取列表时，获取时长="+time);
			m.put("time", time);
			m.put("timeValue", longTime);
		return m;
	}
		//拼接支付需要的参数
	public    Map<String,Object> getPinPaymentResult(Integer amount,OrderItems oi,User u,String customer_ip,UserBrank enterprise){
		Map<String, String> sendMap=new HashMap<>();
		String yearAndMon=enterprise.getExpirationTime();
		String[] ym=yearAndMon.split("/");
		sendMap.put("amount", amount+"");//需要支付的金额
    	sendMap.put("currency", "AUD");
    	sendMap.put("description", oi.getOrderNo());
    	sendMap.put("email", u.getEmail());
    	sendMap.put("ip_address", customer_ip);
    	sendMap.put("card[number]", enterprise.getUbBrankNo());
    	sendMap.put("card[expiry_month]", ym[0]);
    	sendMap.put("card[expiry_year]", ym[1]);
    	sendMap.put("card[cvc]", enterprise.getAfterThree());
    	sendMap.put("card[name]", enterprise.getTheCardholder());
    	sendMap.put("card[address_country]", "Australia");//澳大利亚
    	Map<String,Object> resut=PinPayHttpUtils.sendPinPayChargesPost(sendMap);//支付
    	return resut;
	}
	//通过规划路线拿到里程
	public Double getGooglePlannedRouteMileage(String origins,String destinations,String waypoints){
		Double mileage=0.0;
		Map<String, Object> params = new HashMap<>();
//		 params.put("units", "imperial");
		 System.out.println("司机确认账单时，获取里程origins="+origins);
		 System.out.println("司机确认账单时，获取里程destinations="+destinations);
//		 origins = origins.split("|")[0];//取上一个数组的第一个点 与第二个数组的第一个点
		params.put("origin", origins);//起点纬经度
//		destinations = destinations.split("|")[0];
		params.put("destination", destinations);//终点纬经度 多个点
		params.put("waypoints", waypoints);//途经点
		params.put("key", Constant.GOOGLE_API_KEY);
		String result = "";
		try {
			if(!StringTools.isEmpty(destinations)){
				result = HttpRequestUtil.sendRequestByGet("https://maps.googleapis.com/maps/api/directions/json", params);
			}
			System.out.println("司机确认账单时，获取里程google="+result);
			if(!StringTools.isEmpty(result)){//返回有数据
				JSONObject googleResult=JSONObject.fromObject(result);
				String status=(String) googleResult.get("status");
				if("OK".equals(status)){//如果是成功
//					GoogleMileage gm=(GoogleMileage) JSONObject.toBean(JSONObject.fromObject(), GoogleMileage.class) ;
					JSONArray rowsja = JSONArray.fromObject(googleResult.get("routes"));
					if(rowsja.size()>0){
						Routes rou = (Routes) JSONObject.toBean(JSONObject.fromObject(rowsja.get(0)), Routes.class);
						System.out.println("rou======================="+rou);
						if(rou!=null){
							mileage = rou.getLegs().get(0).getDistance().getValue().doubleValue();
						}
					}
				}
			}
			System.out.println(mileage.getClass().toString());
			System.out.println("司机确认账单时，获取里程="+mileage);
			String mileage1=mileage+"";
			System.out.println(mileage1);
			return mileage;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("司机确认账单时，获取里程异常="+mileage);
			mileage= (double)-1;
			return mileage;
		}
	}
	
	
	//获取google的地图里程
public Double getGoogleMileage(String origins,String destinations){
	Double mileage=0.0;
	Map<String, Object> params = new HashMap<>();
		 params.put("units", "imperial");
		 System.out.println("司机确认账单时，获取里程origins="+origins);
		 System.out.println("司机确认账单时，获取里程destinations="+destinations);
//		 origins = origins.split("|")[0];//取上一个数组的第一个点 与第二个数组的第一个点
		params.put("origins", origins);//起点纬经度
//		destinations = destinations.split("|")[0];
		params.put("destinations", destinations);//终点纬经度 多个点
		params.put("key", Constant.GOOGLE_API_KEY);
		String result = "";
		try {
			
			if(!StringTools.isEmpty(destinations)){
				result = HttpRequestUtil.sendRequestByGet("https://maps.googleapis.com/maps/api/distancematrix/json", params);
			}
			System.out.println("司机确认账单时，获取里程google="+result);
			if(!StringTools.isEmpty(result)){//返回有数据
				JSONObject googleResult=JSONObject.fromObject(result);
				String status=(String) googleResult.get("status");
				if("OK".equals(status)){//如果是成功
//					GoogleMileage gm=(GoogleMileage) JSONObject.toBean(JSONObject.fromObject(), GoogleMileage.class) ;
					JSONArray rowsja = JSONArray.fromObject(googleResult.get("rows"));
					if(rowsja.size()>0){
//						GoogleMileage gm=(GoogleMileage) JSONObject.toBean(JSONObject.fromObject(rowsja.get(0)), GoogleMileage.class) ;
						List<GoogleMileage> gmlist=JSONArray.toList(JSONArray.fromObject(rowsja), GoogleMileage.class) ;
						if(gmlist.size()>0){
							for(GoogleMileage gm:gmlist){
								List<GoogleMileageElementsObj> elementslist=JSONArray.toList(JSONArray.fromObject(gm.getElements()),GoogleMileageElementsObj.class);
								System.out.println("GoogleMileageElements ===="+elementslist);
//								GoogleMileageElementsObj elements =elementslist.get(0);
//								System.out.println("elements="+elements);
//								for(GoogleMileageElementsObj gmeo:elementslist){
								if(elementslist.size()>0){
									GoogleMileageElementsObj gmeo =elementslist.get(0);
									if("OK".equals(gmeo.getStatus())){
										mileage+=gmeo.getDistance().getValue();
									}
								}
//								}
							}
						}
					}
				}
			}
			System.out.println(mileage.getClass().toString());
			System.out.println("司机确认账单时，获取里程="+mileage);
			String mileage1=mileage+"";
			System.out.println(mileage1);
			return mileage;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("司机确认账单时，获取里程异常="+mileage);
			mileage= (double)0;
			return mileage;
		}
}
	
	
	
	@Override
	public ReturnData driverOrderDetail(Long orderId) {
		Map<String, Object> map1 = new HashMap<>();
		Map<String, Object> map = new HashMap<>();
		map1.put("orderId", orderId);
		try {
			OrderItemsAndDriver oiad = orderItemsMapper.getOrderDetail(map1);// 查询订单的星星
			if (oiad != null) {
				map.put("orderId", orderId);
				map.put("uName", oiad.getName());
				map.put("picture", oiad.getPicture());
				map.put("arrived_location", oiad.getArrivedLocation());
				map.put("createTime", oiad.getCreateTime());
				map.put("departureLocation", oiad.getDepartureLocation());
				map.put("departurePosition", oiad.getDeparturePosition());
				map.put("arrivedPosition", oiad.getArrivedPosition());
				map.put("wayToPlaceJingwei", oiad.getWayToPlaceJingwei());
				map.put("wayToPlace", oiad.getWayToPlace());
				map.put("money", oiad.getTotalPrice());
				map.put("carType", oiad.getCarType());
				map.put("totalPrice", oiad.getTotalPrice());
				map.put("status", oiad.getStatus());
			}
			return new ReturnData(map, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}
	}

	@Override
	public ReturnData driverOrder(Long driverId, Integer pageNo, Integer pageSize) {
		Map<String, Object> map1 = new HashMap<>();
		Map<String, Object> map = new HashMap<>();
		map1.put("dirberId", driverId);
		if (RegexUtil.isNull(pageNo)) {
			pageNo = 1;
		}
		if (RegexUtil.isNull(pageSize)) {
			pageSize = 10;
		}
		Integer [] status={2,3,4,5};
		Integer [] status1={7,8,9,10,12,13,14};
		try {
			map1.put("orderStatus", status);
			List<OrderItems> list1 = orderItemsMapper.getOrderItems(map1);
			map.put("unfinished", list1);
			map1.remove("orderStatus");
			map1.put("orderStatus", status1);
			PageHelper.startPage(pageNo, pageSize);
			List<OrderItems> list = orderItemsMapper.getOrderItems(map1);// 查询订单的星星
           for(OrderItems oi:list){
        	   OrderChargeDetail ocd= orderChargeDetailMapper.getOrderChargeDetailPart(oi.getId());
        	   DecimalFormat df = new DecimalFormat("###0.00");
        	   if(ocd!=null){
        		   String trafficJamPrice=ocd.getTrafficJamPrice()==null?"0.00":df.format(ocd.getTrafficJamPrice());
        		   String tips=ocd.getTip()==null?"0.00":df.format(ocd.getTip());
        		   oi.setTrafficJamPrice(trafficJamPrice);
        		   oi.setTips(tips);
        	   }
			}
			map.put("completed", list);
			return new ReturnData(map, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}
	}

	@Override
	public ReturnData hasServicedriverOrderDetail(Long orderId) {
		Map<String, Object> map1 = new HashMap<>();
		Map<String, Object> map = new HashMap<>();
		Map<String, Object> map2 = new HashMap<>();
		Map<String, Object> map3 = null;
		map1.put("orderId", orderId);
		try {
			// licensePlate
			OrderItems oi = orderItemsMapper.selectByPrimaryKey(orderId);
			// OrderItemsAndDriver
			// oi=orderItemsMapper.getOrderDetail(map1);//查询订单的星星
			if (oi != null) {
				map2.put("createTime", oi.getCreateTime());
				map2.put("departureLocation", oi.getDepartureLocation());
				map2.put("arrivedLocation", oi.getArrivedLocation());
				map2.put("carType", oi.getCarType());
				map2.put("departurePosition", oi.getDeparturePosition());
				map2.put("arrivedPosition", oi.getArrivedPosition());
				map2.put("wayToPlaceJingwei", oi.getWayToPlaceJingwei());
				map2.put("wayToPlace", oi.getWayToPlace());
				map2.put("status", oi.getStatus());
				map2.put("departureLocationAll", oi.getDepartureLocationAll());
				map2.put("arrivedLocationAll", oi.getArrivedLocationAll());
				map2.put("wayToPlaceAll", oi.getWayToPlaceAll());
			}
			map.put("oi", map2);
			List<OrderChargeDetail> list = orderChargeDetailMapper.getOrderChargeDetail(map1);
			if (list.size() > 0) {
			map3=ocdObj(list.get(0));
			}
			map.put("ocd", map3);
			Double star = -1.0;
			String context=null;
			String context1=null;
			Double star1 = -1.0;
			List<StarRemark> startRemarkList = starRemarkMapper.getStarRemarkList1(map1);
			for (StarRemark sr : startRemarkList) {
				if (sr.getDriverToUserLabelling() != null) {
					star1 = sr.getStar();
					context1=sr.getContent();
				}
				if (sr.getUserToDriverLabelling() != null) {
					star = sr.getStar();
					context=sr.getContent();
				}
			}
			map.put("passengers_appraise", star);// 乘客对司机的评价星
			map.put("driver_appraise", star1);// 司机对乘客的评价星
			map.put("passengers_context", context);// 乘客对司机的评价星
			map.put("driver_context", context1);// 司机对乘客的评价星
			return new ReturnData(map, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}
	}

	private Map<String,Object> ocdObj(OrderChargeDetail ocd ){
		DecimalFormat df = new DecimalFormat("###0.00");
		Map<String, Object> map3 = new HashMap<>();
		map3.put("orderId", ocd.getOrderId());
		map3.put("driverId", ocd.getDriverId());
		map3.put("id", ocd.getId());
		map3.put("uId", ocd.getuId());
		map3.put("mileageMoney", df.format(ocd.getMileageMoney()));
		map3.put("mileage", df.format(ocd.getMileage()));
		map3.put("time", df.format(ocd.getTime()));
		map3.put("timeFee", df.format(ocd.getTimeFee()));
		map3.put("startFee", df.format(ocd.getStartFee()));
		map3.put("serveiceCharge", df.format(ocd.getServeiceCharge()));
		map3.put("totalFee", df.format(ocd.getTotalFee()));
		map3.put("totals", df.format(ocd.getTotals()));
		map3.put("totalMoney", df.format(ocd.getTotalMoney()));
		map3.put("cId", ocd.getcId());
		map3.put("type", ocd.getType());
		map3.put("tip", df.format(ocd.getTip()));
		map3.put("cleanness_img", ocd.getCleanness_img());
		map3.put("cleanness_remark", ocd.getCleanness_remark());
		map3.put("cleaning_fee_audit", ocd.getCleaning_fee_audit());
		map3.put("cleanness", df.format(ocd.getCleanness()));
		map3.put("trafficJamPrice", df.format(ocd.getTrafficJamPrice()));
		map3.put("minimumFare", df.format(ocd.getMinimumFare()));
		map3.put("bookingFee", df.format(ocd.getBookingFee()));
		map3.put("createTime", ocd.getCreateTime().getTime());
		map3.put("couponMoney", df.format(ocd.getCouponMoney()));
		map3.put("orderDriverSettlement", df.format(ocd.getOrderDriverSettlement()));
		map3.put("orderFabCommissions", df.format(ocd.getOrderFabCommissions()));
		map3.put("cancelFee", df.format(ocd.getCancelFee()));
		map3.put("concierge_price", df.format(ocd.getConcierge_price()));
		map3.put("carType", ocd.getCalType());
		return map3;
	}
	/**
	 * 确认订车 网络不好提示网络：网络异常，请检查网络 确认订车 车辆被他人优先预订提示：你慢了一步，车辆已被预订 确认订车
	 * 司机下线，提示：司机暂时不服务，请重新选择 确认订车 司机已服务12小时，提示：司机今日已结束服务
	 */
	@Override
	public ReturnData confirmTheOrdering(Long driverId, Long orderId,HttpServletRequest request) {
		Driver d = userMapper.driverState(driverId);
		Map<String, Object> map = new HashMap<>();
		map.put("dirberId", driverId);// 查询我的订单
		Integer[] orderStatus = {  2, 3, 4, 5, 6, 7, 15 };// 未完成支付
		map.put("orderStatus", orderStatus);
		Map<String, Object> map1 = new HashMap<>();
		map1.put("isUse", 1);
		map1.put("uId", driverId);
		try {
			User u = userMapper.selectByPrimaryKey(driverId);// 司机信息
			if (d != null) {// 司机状态
				if (d.getIsOnline() == 2) {
					return new ReturnData(201, "Driver temporarily offline, please select a new ride.");
				}
				if(d.getNotOrder()!=null&&d.getNotOrder()!=1){
					return new ReturnData(209, "The driver is now being punished. Can't order");
				}
				OrderItems oi = orderItemsMapper.selectByPrimaryKey(orderId);
				if (oi == null) {
					return new ReturnData(209, "Invalid Order");
				}
				List<DriverAccessory> li=driverAccessoryMapper.getCar(map1);
				if(li.size()>0){
					oi.setCarId(li.get(0).getId());
				}
				if(d.getServerStatus()==1){//如果司机的状态是服务中的  那么才判断司机是否是十分钟之内会结束订单
					Map<String, Object> mapp = new HashMap<>();
					Long[] dr = { driverId };
					mapp.put("driverIds", dr);// 司机
					List<GisRecord> grlist = gisRecordMapper.selectByDriverId(mapp);
					if (grlist.size() > 0) {
						GisRecord gr = grlist.get(0);
						long diff = gr.getTimes();// 结束服务的时间-当前时间
						// 大于3分钟
						// 不可接单
							long diffMinutes = 0;
							if(diff!=0){
							diffMinutes=diff /  60;
							}
						if (gr.getTimes()>0&&diffMinutes<=10) {//10分钟之内
							oi.setUpTime(new Date());// 用户确认订车时间
							oi.setDirberId(driverId);
							oi.setStatus(2);
							int num = orderItemsMapper.updateByPrimaryKeySelective(oi);
							if(num==0){
								return new ReturnData(206,"update fail");
							}
							FireBaseUtil.sendMessageAlertAndSoundOrder(u.getUseEquipment(), "You have a new trip request!.");
							return new ReturnData(oi,200,"update success");
						}
					}
				}
				oi.setUpTime(new Date());// 用户确认订车时间
				oi.setDirberId(driverId);
				int num = orderItemsMapper.updateByPrimaryKeySelective(oi);
				if (num != 0) {
					FireBaseUtil.sendMessageAlertAndSoundOrder(u.getUseEquipment(), "You have a new trip request!.");
					FireBaseUtil.postDataForFireBaseDataBase(u.getId()+"", "{\"orderId\":" + oi.getId() + ",\"type\":1,\"status\":1}");
					UserMessage um = new UserMessage();// 记录消息
					um.setCreateTime(new Date());
					um.setmContext("You have a new trip request!.");
					um.setmName("You have a new trip request!.");
					um.setmSummary("You have a new trip request!.");
					um.setName(u.getName());
					um.setType(2);// 1用户端 2司机端
					um.setuId(driverId);
					int n1 = userMessageMapper.insertSelective(um);// 添加
					UserConfirmTheOrdering ucto = new UserConfirmTheOrdering();
					ucto.setCreateTime(new Date());
					ucto.setDriverId(driverId);
					ucto.setOrderId(oi.getId()); 
					ucto.setDifference(1);//区别  1用户端 用户确认订车  司机为空闲状态没有接单 15分钟内不能接单  2.司机取消超过多少次被惩罚
					userConfirmTheOrderingMapper.insertSelective(ucto);//保存该数据 用户后期惩罚司机   司机未按时接单 将有15分钟不能接单【不会出现在用户的司机列表中】
					return new ReturnData(oi,200, "Wait for the driver to take the order");
				} else {
					return new ReturnData(209, "update fail");
				}
			} else {
				return new ReturnData(209, "I didn't find the driver");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}

	}
	@Override
	public Object normalCharge(Long orderId, Integer carType, Integer language) {
		if (orderId == null) {
			return new ReturnData(301, "The order ID cannot be empty.");
		} else if (language == null) {
			return new ReturnData(306, "Language cannot be empty.");
		}
		try {
			OrderItems ooi = orderItemsMapper.selectByPrimaryKey(orderId);// 通过订单id查询订单
			ooi.setCarType(carType);
			int num = orderItemsMapper.updateByPrimaryKeySelective(ooi);// 更新订单状态
			if (num == 0) {
				return new ReturnData(201, LanguageUtils.returnLan(language, "fail_order_update"));
			}
			String type="";
			switch (carType) {
			case 1:
				type="fab ONE";
				break;
			case 2:
				type="fab";
				break;
			case 3:
				type="fab PRO";
				break;
			}
			User u = userMapper.selectByPrimaryKey(ooi.getuId());
			FireBaseUtil.sendMessageAlert(u.getUseEquipment(), "Driver has adjusted to different service category based on the number of riders in the car.");
//			SendPushNotification.sendMessageAlertUser(u.getUseEquipment(), "Driver has adjusted to different service category based on the number of riders in the car.");
//			AuroraPush.pushTargetAlertForUser(u.getUseEquipment(), "Driver has adjusted to different service category based on the number of riders in the car.", u.getAuroraAlias());
			return new ReturnData(200, LanguageUtils.returnLan(language, "successful_order_update"));
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}
	}

	@Override
	public Object selectById(Long orderId) {
		Map<String,Object> map3=new HashMap<>();
		Jedis jedis=null;
		if(jedis==null){
			jedis = jedisPool.getResource();
		}
		try {
			OrderItems ooi = orderItemsMapper.selectByPrimaryKey(orderId);
			ConfigManager cm=null;
 			String configManager=jedis.get("configManager");
 			if(StringTools.isEmpty(configManager)){
 				 cm = configManagerMapper.selectByPrimaryKey(1);
 					JSONObject jo = JSONObject.fromObject(cm);
 					jedis.set("configManager", jo.toString());
 			}else{
 				JSONObject jo = JSONObject.fromObject(configManager);
 				cm = (ConfigManager) JSONObject.toBean(jo, ConfigManager.class);
 			}
 			if (cm!=null) {
 				ooi.setConfigTime(cm.getOrderTime());
 			}
			User u = userMapper.selectByPrimaryKey(ooi.getuId());
			if(u!=null){
				ooi.setUserPicture(u.getPicture());
				Map<String, Object> map1 = new HashMap<>();
				map1.put("dirberId", u.getId());
				Integer count = orderItemsMapper.getDriverOrderCount(map1);//
				u.setCounts(count+"");
			}
			Map<String,Object> map = new HashMap<>();
//			map.put("orderId", orderId);
			map.put("uId", ooi.getuId());
			map.put("type", 2);
			 List<StarRemark> l1=starRemarkMapper.getStarRemarkList1(map);
			 if(l1.size()>0){
				 ooi.setStar(l1.get(0).getStar()+"");//评价星级
			 }
			 ooi.setRemark(u.getRemark()+"");
			 map.put("orderId", orderId);
			 List<OrderChargeDetail> list= orderChargeDetailMapper.getOrderChargeDetail(map);
			 if(list.size()>0){//订单详情
				 map3=ocdObj(list.get(0));
				 ooi.setOcd(map3);
				 ooi.setBookingFee(list.get(0).getBookingFee()+"");
				 ooi.setServeiceCharge(list.get(0).getServeiceCharge()+"");
				 ooi.setStartFee(list.get(0).getStartFee()+"");
				 ooi.setMileage(list.get(0).getMileage());
				 ooi.setMileageMoney(list.get(0).getMileageMoney()+"");
				 ooi.setMinimumFare(list.get(0).getMinimumFare()+"");
				 ooi.setTime(list.get(0).getTime()+"");
				 ooi.setTimeFee(list.get(0).getTimeFee()+"");
			 }
			ooi.setNowTime(new Date().getTime());
			return new ReturnData(ooi, 200, "success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}finally {
			if(jedis!=null){
				jedis.close();
			}
		}
	}

	@Override
	public Object getMyItineraryNotShowDel(Long orderId) {
		OrderItems ooi = orderItemsMapper.selectByPrimaryKey(orderId);
		ooi.setIsShow(2);// 1 显示 2不显示
		try {
			int num = orderItemsMapper.updateByPrimaryKeySelective(ooi);
			if (num == 0) {
				return new ReturnData(201, "Delete failed");
			}
			return new ReturnData(200, "Delete success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}
	}

	// 打赏 支付
	@Override
	public Object exceptionalTip(String json) {
    OrderItems oi = StringTools.json2Obj(json, OrderItems.class);
		if(oi==null){
			return new ReturnData(201,LanguageUtils.returnLan(oi.getLanguage(), "list_empty"));
		}
		int code=200;String msg=LanguageUtils.returnLan(oi.getLanguage(), "exceptional_success");
		String jrc =null;
		try {
			UserBrank ub = userBrankMapper.selectByPrimaryKey(oi.getUbId());//支付的银行卡
			OrderItems ooi=orderItemsMapper.selectByPrimaryKey(oi.getOrderId());//查询订单
			User u = userMapper.selectByPrimaryKey(ooi.getuId());//查询用户  记录 统计用户的消费金额 与里程
			/////////打赏 支付/////////
//			String yearAndMon=ub.getExpirationTime();
//			String[] ym=yearAndMon.split("/");
//			
//					Map<String, String> sendMap=new HashMap<>();
//			    	
//			    	sendMap.put("amount", tos+"");//需要支付的金额
//			    	sendMap.put("currency", "AUD");
//			    	sendMap.put("description", ooi.getOrderNo());
//			    	sendMap.put("email", u.getEmail());
//			    	sendMap.put("ip_address", oi.getCustomer_ip());
//			    	sendMap.put("card[number]", ub.getUbBrankNo());
//			    	sendMap.put("card[expiry_month]", ym[0]);
//			    	sendMap.put("card[expiry_year]", ym[1]);
//			    	sendMap.put("card[cvc]", ub.getAfterThree());
//			    	sendMap.put("card[name]", ub.getTheCardholder());
////			    	sendMap.put("card[address_line1]", ub.getAddressLine1());
////			      	sendMap.put("card[address_city]", ub.getAddressCity());
//			    	sendMap.put("card[address_country]", "Australia");//澳大利亚
			Integer tos=(int) (oi.getExceptionalATip().doubleValue()*100);//打赏金额
					Map<String,Object> resut=getPinPaymentResult(tos,ooi,u,oi.getCustomer_ip(),ub);//支付
			    	  if(resut.get("code")!=null&&(int)resut.get("code")==201){//支付成功
			    		  ResponseCharges rc=(ResponseCharges) resut.get("obj");
			    		   jrc = JSONObject.fromObject(rc).toString();
			   		}else if(resut.get("code")!=null&&(int)resut.get("code")==422){
			   			ErrorResponseCard rc=(ErrorResponseCard) resut.get("obj");
			   			String error="";
			   			if(rc!=null){
			   				List<ErrorMessage> liMessage=JSONArray.toList(JSONArray.fromObject(rc.getMessages()), ErrorMessage.class);
			                for(ErrorMessage ee:liMessage){
			              	  error+=ee.getMessage()+" ; "; 
			                }
			   			}
			   			jrc =  JSONObject.fromObject(rc).toString();
			   			return new ReturnData(900,error);
			   		}else if(resut.get("code")!=null&&(int)resut.get("code")==400){
			   			ErrorResponse400 rc=(ErrorResponse400) resut.get("obj");
			   			jrc = JSONObject.fromObject(rc).toString();
			   			return new ReturnData(300,rc.getError_description());
					}
			      PinpayRecord ppr = new PinpayRecord(oi.getId(),jrc,(int)resut.get("code"),new Date(),1);//支付记录
		  		  pinpayRecordMapper.insertSelective(ppr);//保存交易记录
			/////////
			if(code==200){
				Map<String,Object> map = new HashMap<>();
				map.put("orderId", ooi.getId());
				ooi.setExceptionalATip(oi.getExceptionalATip());//更新订单中打赏的小费金额
				int n=	orderItemsMapper.updateByPrimaryKeySelective(ooi);//更新订单打赏金额
				 if(n==0){
					 code=210;msg=LanguageUtils.returnLan(oi.getLanguage(), "fail_order_update");
				 }
				List<OrderChargeDetail> locd=orderChargeDetailMapper.getOrderChargeDetail(map);
				if(locd.size()>0){
					OrderChargeDetail ocd=locd.get(0);
					ocd.setTip(oi.getExceptionalATip().doubleValue());
					ocd.setOrderDriverSettlement(ocd.getOrderDriverSettlement()+oi.getExceptionalATip().doubleValue());//该订单司机需要结算的费用+小费 //周末一起划账
					int n1=orderChargeDetailMapper.updateByPrimaryKeySelective(ocd);//更新订单的打赏费用
					 if(n1==0){
						 code=210;msg=LanguageUtils.returnLan(oi.getLanguage(), "fail_order_update");
					 }
				}
					 UserMessage um = new UserMessage();
					 um.setCreateTime(new Date());
					 um.setmContext("Rider left $"+oi.getExceptionalATip()+" AUD tips");
					 um.setmName("Rider Tips");
					 um.setmSummary("Rider Tips");
					 um.setType(2);//司机查看
					 um.setuId(ooi.getuId());
					int umnum= userMessageMapper.insertSelective(um);
					//打赏记录表存入数据 平台周结算时一起结算
					PlayTheRewardReward ptrr = new PlayTheRewardReward();
					ptrr.setAmout(oi.getExceptionalATip().doubleValue());
					ptrr.setCreateTime(new Date());
					ptrr.setOrderId(ooi.getId());
					ptrr.setType(1);
					ptrr.setuId(ooi.getDirberId());//打赏给谁的
					playTheRewardRewardMapper.insertSelective(ptrr);//保存打赏记录 用户周结算
					User driver =userMapper.selectByPrimaryKey(ooi.getDirberId());//查询司机信息 
					FireBaseUtil.sendMessageAlert(driver.getUseEquipment(), "Rider left $"+oi.getExceptionalATip()+" AUD tips");
					FireBaseUtil.postDataForFireBaseDataBase(driver.getId()+"", "{\"type\":5,\"orderId\":0,\"status\":0,\"amount\":"+oi.getExceptionalATip()+"}");
			}
			return new ReturnData(code,msg);
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}
	}
  //支付余额不足的订单
	@Override
	public ReturnData payLessThan(String json) {
		OrderItems oi = StringTools.json2Obj(json, OrderItems.class);
		OrderItems ooi=orderItemsMapper.selectByPrimaryKey(oi.getOrderId());//查询订单
		if(ooi==null){//
			return new ReturnData(201, "List must be filled！");
		}
		int code=200;String msg="";	String jrc="";int status=14;String jrc1="";
		Jedis jedis = null;
		if(jedis==null){
			jedis =jedisPool.getResource();
		}
		try {
			User u = userMapper.selectByPrimaryKey(ooi.getuId());
			UserBrank ub=userBrankMapper.selectByPrimaryKey(ooi.getUbId());
			Map<String,Object> map = new HashMap<>();
			map.put("orderId", oi.getOrderId());
		List<OrderChargeDetail> li=	orderChargeDetailMapper.getOrderChargeDetail(map);
	       Integer totalPrice=	(int) (ooi.getTotalPrice().doubleValue()*100);
	    	Map<String,Object> resut=getPinPaymentResult(totalPrice, ooi,u,oi.getCustomer_ip(),ub);//支付
	    	  if(resut.get("code")!=null&&(int)resut.get("code")==201){//支付成功
	    		  ResponseCharges rc=(ResponseCharges) resut.get("obj");
	    		  jrc = JSONObject.fromObject(rc).toString();
//	    		  ConfigManager cm=configManagerMapper.selectByPrimaryKey(1);//查询配置信息
	    		  ConfigManager cm=null;
	   			String configManager=jedis.get("configManager");
	   			if(StringTools.isEmpty(configManager)){
	   				 cm = configManagerMapper.selectByPrimaryKey(1);
	   					JSONObject jo = JSONObject.fromObject(cm);
	   					jedis.set("configManager", jo.toString());
	   			}else{
	   				JSONObject jo = JSONObject.fromObject(configManager);
	   				cm = (ConfigManager) JSONObject.toBean(jo, ConfigManager.class);
	   			}
		    		Map<String, String> fabMap=new HashMap<>();
		    		fabMap.put("amount", (int)(li.get(0).getOrderFabCommissions()*100)+"");//需要支付的金额
		    		fabMap.put("currency", "AUD");
		    		fabMap.put("description", ooi.getOrderNo()+"  the order platform for $"+li.get(0).getOrderFabCommissions());
		    		fabMap.put("recipient", cm.getFab_token());//收件人凭证
			    	Map<String,Object> fabresult=  PinPayHttpUtils.sendPinPayCreateTransfersPost(fabMap);
			    	 if(fabresult.get("code")!=null&&(int)fabresult.get("code")==201){//支付成功
			    		 ResponseTransfers rc1=(ResponseTransfers) fabresult.get("obj");
			    		   jrc1 = JSONObject.fromObject(rc1).toString();
			   		}else if(fabresult.get("code")!=null&&(int)fabresult.get("code")==422){
			   			ErrorResponseCard rc1=(ErrorResponseCard) fabresult.get("obj");
			   					 						   			code=900;
			   			jrc1 =  JSONObject.fromObject(rc1).toString();
			   		}else if(fabresult.get("code")!=null&&(int)fabresult.get("code")==400){
			   			ErrorResponse400 rc1=(ErrorResponse400) fabresult.get("obj");
//			   		    ReturnData rd=ChooseDeductions(oi, u, oi.getuId(), oi.getUbId(), amount, ocd.getCustomer_ip());//扣取没有拿到的钱
//			   		    code=rd.getCode(); //			 						   			code=900;
				   		jrc1 =  JSONObject.fromObject(rc1).toString();;
					}
			    	 PinpayRecord fabppr = new PinpayRecord(oi.getId(),jrc1,(int)fabresult.get("code"),new Date(),3);//支付记录
		    		 pinpayRecordMapper.insertSelective(fabppr);  
		    		 status=8;
	    	  }else if(resut.get("code")!=null&&(int)resut.get("code")==422){
		   			ErrorResponseCard rc=(ErrorResponseCard) resut.get("obj");
		   			String error="";
		   			if(rc!=null){
		   				List<ErrorMessage> liMessage=JSONArray.toList(JSONArray.fromObject(rc.getMessages()), ErrorMessage.class);
		                for(ErrorMessage ee:liMessage){
		              	  error+=ee.getMessage()+" ; "; 
		                }
		   			}
		   			code=900;
		   			jrc =  JSONObject.fromObject(rc).toString();;msg=error;
		   		}else if(resut.get("code")!=null&&(int)resut.get("code")==400){
		   			ErrorResponse400 rc=(ErrorResponse400) resut.get("obj");
		   			jrc = JSONObject.fromObject(rc).toString();
		   			code=900;msg=rc.getError_description();
				}
		    	  PinpayRecord ppr = new PinpayRecord(oi.getId(),jrc,(int)resut.get("code"),new Date(),4);//支付记录
	    		  pinpayRecordMapper.insertSelective(ppr);
	    		if(ooi.getStatus()==11){
	    			  ooi.setStatus(12);//修改订单状态
	    		}else{
	    			ooi.setStatus(8);//修改订单状态
	    		}
	    		 int num=orderItemsMapper.updateByPrimaryKeySelective(ooi);
			return new ReturnData(code,msg);
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}finally {
			if(jedis!=null){
				jedis.close();
			}
		}
	}

	@Override
	public ReturnData isNotConcierge(Double lng, Double lat, String cityName) {
		Map<String, Object> map = new HashMap<>();
		if (!StringTools.isEmpty(cityName)) {
			map.put("cityName", cityName);
		}
		map.put("identity", 2);
		Jedis jedis = null;
		if(jedis==null){
			jedis =jedisPool.getResource();
		}
		try {
			List<CityRecord> list = cityRecordMapper.getList(map);// 查询服务于该城市的司机
			if (list.size() > 0) {
				map.put("cityId", list.get(0).getId());
			}
			ConfigManager cm=null;double concierge_mileage_distance=0.0;double concierge_time=0.0;
			String configManager=jedis.get("configManager");
			if(StringTools.isEmpty(configManager)){
				 cm = configManagerMapper.selectByPrimaryKey(1);
					JSONObject jo = JSONObject.fromObject(cm);
					jedis.set("configManager", jo.toString());
				concierge_mileage_distance = cm.getConcierge_mileage_distance();
				concierge_time=cm.getConcierge_time();
			}else{
				JSONObject jo = JSONObject.fromObject(configManager);
				cm = (ConfigManager) JSONObject.toBean(jo, ConfigManager.class);
				concierge_mileage_distance = cm.getConcierge_mileage_distance();
				concierge_time=cm.getConcierge_time();
			}
			List<Map> listMap=orderItemsMapper.isNotConcierge();
			Iterator<Map> it = listMap.iterator();
			 int count=listMap.size();long ltime=0;
			while (it.hasNext()) {
				Map m= it.next();
				String poList= (String) m.get("position");
				JSONArray j=JSONArray.fromObject(poList);
				if(!j.isEmpty()){
					String position=(String) j.get(j.size()-1);
					String [] positionlist=position.split(",");
					Double lng1=Double.parseDouble(positionlist[0]);Double lat1=Double.parseDouble(positionlist[1]);
					double distance =Distance.getDistance(lng1, lat1, lng, lat);//司机与乘客相距的距离
					String pos=lat1+","+lng1;
					String pos1=lng+","+lat;
					Map<String,Object> fromTheTime=getGoogleTimes(pos,pos1);
					ltime = (long) fromTheTime.get("timeValue");
					if(distance>concierge_mileage_distance||ltime>concierge_time){//距离超过五公里 就不显示
						it.remove();
						--count;
					}
				}
			}
			if(count>0){
				return new ReturnData(count,200,"success");
			}
			return new ReturnData(count,201,"fail");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}finally {
			if(jedis!=null){
				jedis.close();
			}
		}
	}

	@Override
	public ReturnData saveViaPoint(Long orderId,Integer type,Long uId) {
		Jedis jedis = null;
		if(jedis==null){
			jedis =jedisPool.getResource();
		}
		try {
		String viap=	jedis.get("viaPoint_"+orderId);
		if(type==1){//存
			jedis.set("viaPoint_"+orderId,"1");
			FireBaseUtil.sendMessageAlertAndChangeAddress(uId+"", "It's time to go");
			FireBaseUtil.postDataForFireBaseDataBase(uId+"", "{\"type\":20,\"orderId\":"+orderId+",\"status\":\"1\"}");
			return new ReturnData(1,200,"success");
		}
		if(StringTools.isEmpty(viap)){
			viap="0";
		}
		return new ReturnData(viap,200,"success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}finally {
			if(jedis!=null){
				jedis.close();
			}
		}
	}
 
	@Override
	public ReturnData driverDidNotCancelOrder(Long orderId, Long driverId) {
		Map<String,Object> map = new HashMap<>();
		map.put("driverId", driverId);
		map.put("orderId", orderId);
		try {
			List<UserConfirmTheOrdering> list= userConfirmTheOrderingMapper.getUserConfirmTheOrdering(map);
			OrderItems oi=orderItemsMapper.selectByPrimaryKey(orderId);
			for(UserConfirmTheOrdering uct:list){
				userConfirmTheOrderingMapper.deleteByPrimaryKey(uct.getId());
			}
			if(oi.getStatus()==1){//订单状态为1  代表司机还没有接单 取消是不算做取消次数的
				oi.setStatus(16);//用户在 司机未接单时取消
				punishment(oi.getuId());//司机取消惩罚
				orderItemsMapper.updateByPrimaryKeySelective(oi);//
				FireBaseUtil.sendMessageAlertAndChangeAddress(oi.getuId()+"", "It has reached the passing point.");
    			FireBaseUtil.postDataForFireBaseDataBase(oi.getuId()+"", "{\"orderId\":" + orderId + ",\"type\":1,\"status\":16}");
				return new ReturnData(200,"The driver refused to take the order.");
			}
			return new ReturnData(200,"success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500, "Wow, that's wrong");
		}
		
	}

}
